Skip to content
On this page

Arrays

Underscore provides many utility methods for easier and quicker manipulation of arrays.

first / last

As the names imply, these two functions retrieve the first and last elements, respectively:

javascript
let arr = [2, 4, 6, 8];
_.first(arr); // 2
_.last(arr); // 8

flatten

flatten() takes an array and transforms it into a one-dimensional array, regardless of how many nested arrays it contains:

javascript
_.flatten([1, [2], [3, [[4], [5]]]]); // [1, 2, 3, 4, 5]

zip / unzip

zip() aligns the elements of two or more arrays by their indices and merges them into a new array. For example, if you have one array of names and another of scores, zip() makes it easy to match them:

javascript
let names = ['Adam', 'Lisa', 'Bart'];
let scores = [85, 92, 59];
_.zip(names, scores);
// [['Adam', 85], ['Lisa', 92], ['Bart', 59]]

unzip() does the reverse:

javascript
let namesAndScores = [['Adam', 85], ['Lisa', 92], ['Bart', 59]];
_.unzip(namesAndScores);
// [['Adam', 'Lisa', 'Bart'], [85, 92, 59]]

object

Sometimes, instead of using zip(), you might want to directly map names to scores in an object. The object() function does just that:

javascript
let names = ['Adam', 'Lisa', 'Bart'];
let scores = [85, 92, 59];
_.object(names, scores);
// {Adam: 85, Lisa: 92, Bart: 59}

Note that _.object() is a function, not the JavaScript Object object.

range

range() allows you to quickly generate a sequence without needing a for loop:

javascript
// Start from 0, less than 10:
_.range(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

// Start from 1, less than 11:
_.range(1, 11); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Start from 0, less than 30, step 5:
_.range(0, 30, 5); // [0, 5, 10, 15, 20, 25]

// Start from 0, greater than -10, step -1:
_.range(0, -10, -1); // [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

For more complete functions, please refer to the Underscore documentation: https://underscorejs.org/#arrays

Exercise

Use _.uniq to remove duplicate elements from an array in a case-insensitive manner:

javascript
let arr = ['Apple', 'orange', 'banana', 'ORANGE', 'apple', 'PEAR'];
let result = ???

// Test
if (result.toString() === ["Apple", "orange", "banana", "PEAR"].toString()) {
    console.log('Test successful!');
} else {
    console.log('Test failed!');
}
Arrays has loaded