Home » Underscore » Underscore arrays

Underscore arrays

Welcome to the second module of Undersore.js tutorial. In this Module we will cover some basic concepts of underscore arrays, how arrays can fetch the value from an object, how arrays can be used to manipulate fetched value. As we move, we will learn about each of the collection that underscore provides.

So let’s go through each array function one by one.

_.first(array, [n])
_.first() function returns first n number of elements.
Passing nothing will return only 1st element.


var firstNumber = _.first(numberArray, 5);

// console: 1, 2, 3, 4, 5

var firstPerson = _.first(objectArray, 3);

// console: Will return first 3 objects


_.initial(array, [n])
_.initial() function returns all except the last n values.
Passing nothing will remove last value.

var initialNumber = _.initial(numberArray, 5); 

// console: 1, 2, 3, 4

var initialPerson = _.initial(objectArray);

// console: return allobject except the last one


_.last(array, [n])
_.last() function returns last n values.
Passing nothing will return last 1 value.

var lastNumbers = _.last(numberArray, 3);

// console: 7, 8, 9

var lastPerson = _.last(objectArray);

// console: name: "Piyush", age: 28


_.rest(array, [index])
_.rest() function returns rest of the values.
If we won’t pass any index than it will return all values except first (index: 0)

var restNumber = _.rest(numberArray, 3);

// console: 4, 5, 6, 7, 8, 9

Will remove items till index value 3 (i.e. from index 0 to 3)

var restPerson = _.rest(objectArray);

// console: will return objects other than first value


_.compact() function returns a copy of array which contains only true values.
false, null, 0, “” are considered as false values.

var compactNumber = _.compact([false, true, 1, 0, "",''," ",' ']);

// console: true, 1, " ", ' '


_.flatten(array, [shallow])
_.flatten() function flattens the nested array (i.e. removes all the square brackets), adding true ([shallow]) flatten an array to single value (i.e. remove single level square bracket) and return remaining values as an array.

By default [shallow] is false.

var flattenObject = _.flatten([['a'], [['b']], [2], [[[[['D']]]]]]);

// console: ["a", "b", 2, "D"]
// console: ["a", Array[1], 2, Array[1]]  //pass [shallow] as true


_.without(array, [*values])
_without() function removes all the values passed in [*values] from an array.

var withoutNumber = _.without(numberArray,1,4,6);

// console: [2, 3, 5, 7, 8, 9]


_.union() function returns list of unique items, in order, that are present in one or more of the arrays.

var unionNumber = _.union([1,2,3],["a","b","c"],[12,1,2,3,"a","d","g"]); 

// console: [1, 2, 3, "a", "b", "c", 12, "d", "g"]

Returns an array having unique values from other arrays.


_.intersection() function returns list of values that are present in each array.

var intersectionNumber = _.intersection([1,2,3],["a","b","c",1],[12,1,2,3,"a","d","g"]);

// console: [1]

[1] is a common value in all the arrays.


_.difference(array, *others)
_.difference() function return the values from first array that are not present in any other arrays.

var differenceArray = _.difference([1,2,3],["a","b","c",1],["k",2]);

// console: [3]

from first array [3] is the only value that is not present in other arrays.


_.uniq(array, [isSorted], [iterator])
_.uniq() function returns the unique values. It uses === comparison to detect unique values.
Passing true for isSorted runs faster algorithm, because it considers an array to be sorted array.

var uniqNumber = _.uniq([1,2,"8",3,2,1,1,2,3,4,5,6,7,7,8]);

// console: [1, 2, "8", 3, 4, 5, 6, 7, 8]

Let’s try the above example by passing true as [isSorted]

var uniqNumber = _.uniq([1,2,"8",3,2,1,1,2,3,4,5,6,7,7,8],true);

// console: [1, 2, "8", 3, 2, 1, 2, 3, 4, 5, 6, 7, 8]

Passing true in above example returns some weird result, because it considers an array to be a sorted array.


_.zip() function combines all the array values and returns a new array.
It will return undefined if the values are more in any of the array.
_.zip.apply can transpose the matrix in a similar fashion.

var zippedArray = _.zip(numberArray, objectArray);

// console: [[1,object], [2,object]...[6, object], [7, undefined], [8, undefined], [9, undefined]]

You must have noticed that above example returned undefined in last 3 results; because there are only 6 items in the objectArray.

var zipApply = _.zip.apply([["A","B","C"]], [ ['name','age'], ["Himanshu",26],[1,2] ]);

// console: [["name","Himanshu",1], ["age","26",2]]


_.object(list, [values])
_.object() function takes an array and returns an object in a form of key-value pairs.
There are two ways of passing data to this method.

1st method: Passing list of key and list of values. First array will be key, second will be a value

var objectData = _.object(numberArray,objectArray); 

// console: 1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: undefined, 8: undefined, 9: undefined

2nd method: Passing list of key value pairs

var objectData2 = _.object([['name',"Himanshu"],['age',26],['country',"India"]]);

// console: name: "Himanshu", age: 26, country: "India"


_.indexOf(array, value, [isSorted]) 
_.indexOf() function returns index of a value in an array. You can pass true for “isSorted” if the array is sorted which will run faster algorithm.
If the value is not found then _.indexOf() method returns -1 and if the value has more than 1 occurrence in an array then it returns the index of first occurrence only.

var indexNumber = _.indexOf([1,2,3,4,5,6,7,2,3,4,1], 2);

// console: 1


_.lastIndexOf(array, value, [fromIndex]) 
_.lastIndexOf() function returns the last index of value.

var lastIndex = _.lastIndexOf([1,2,3,4,5,6,7,2,3,4,1], 4);

// console: 9


_.sortedIndex(list, value, [iterator], [context])
_.sortedIndex() function returns the index value where the data should be inserted in an array.

var insertPerson = _.sortedIndex(objectArray, {name:'Tracy', age: 28}, 'age');

// console: 2 This will check the age parameters value
// console: 6 if we pass name as a parameter


_.range([start], stop, [step])
_.range() function generates a list of values from start to stop. But the stop value will not be included in the list.
If we do not pass start it will start from 0.
We can have flexibility in values by changing step value, by default step value is 1. Below are some examples which show the result of _.range() function in various scenarios.

var range1 = _.range(10);

// console: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Start from 0 and go till 9 (stop value will not be in the list)

var range2 = _.range(10,20);

// console: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Start value (10) will be included in the list.

var range3 = _.range(0,50,10);

// console: [0, 10, 20, 30, 40]

Start from 0 (start value), incremented by 10 (step value), stop at 40 (stop value)

var range4 = _.range(0,-50,-10);

// console: [0, -10, -20, -30, -40]

We can pass negative values also.

var range5 = _.range(-50, 50, -10);

// console: []

This will return an empty array, because range starts from -50 and stepping with -10 will return -60 which is not in range.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>