Skip to content
On this page

Collections

Underscore provides a consistent interface for collection objects. Collections refer to both Array and Object, while Map and Set are not currently supported.

map/filter

Similar to Array's map() and filter(), Underscore's map() and filter() can also be applied to Object. When used with Object, the function passed in receives function (value, key), where the first parameter is the value and the second is the key:

javascript
let obj = {
    name: 'bob',
    school: 'No.1 middle school',
    address: 'xueyuan road'
};

let upper = _.map(obj, function (value, key) {
    return value.toUpperCase(); // Convert values to uppercase
});

console.log(JSON.stringify(upper)); // ["BOB", "NO.1 MIDDLE SCHOOL", "XUEYUAN ROAD"]

You might wonder why the result of mapping an Object is an Array. It seems more logical for it to return an Object. Try replacing _.map with _.mapObject to get an Object as the result.

every / some

The _.every() function returns true if all elements in the collection satisfy the condition, while _.some() returns true if at least one element satisfies the condition:

javascript
// Are all elements greater than 0?
_.every([1, 4, 7, -3, -9], (x) => x > 0); // false
// Is at least one element greater than 0?
_.some([1, 4, 7, -3, -9], (x) => x > 0); // true

When the collection is an Object, you can access both the value and the key:

javascript
let obj = {
    name: 'bob',
    school: 'No.1 middle school',
    address: 'xueyuan road'
};

// Check if all keys and values are lowercase:
let r1 = _.every(obj, function (value, key) {
    return key === key.toLowerCase() && value === value.toLowerCase();
});
let r2 = _.some(obj, function (value, key) {
    return key === key.toLowerCase() && value === value.toLowerCase();
});

console.log('every key-value are lowercase: ' + r1 + '\nsome key-value are lowercase: ' + r2);

max / min

These functions return the maximum and minimum values from a collection:

javascript
let arr = [3, 5, 7, 9];
_.max(arr); // 9
_.min(arr); // 3

// An empty collection will return -Infinity and Infinity, so check if it's not empty first:
_.max([]); // -Infinity
_.min([]); // Infinity

Note that if the collection is an Object, max() and min() operate only on the values, ignoring the keys:

javascript
_.max({ a: 1, b: 2, c: 3 }); // 3

groupBy

The groupBy() function categorizes the elements of a collection based on a key returned by the provided function:

javascript
let scores = [20, 81, 75, 40, 91, 59, 77, 66, 72, 88, 99];
let groups = _.groupBy(scores, function (x) {
    if (x < 60) {
        return 'C';
    } else if (x < 80) {
        return 'B';
    } else {
        return 'A';
    }
});
// Result:
// {
//   A: [81, 91, 88, 99],
//   B: [75, 77, 66, 72],
//   C: [20, 40, 59]
// }

As seen, groupBy() is very convenient for grouping.

shuffle / sample

The shuffle() function randomly rearranges the elements of a collection using a shuffling algorithm:

javascript
// Note that the result is different each time:
_.shuffle([1, 2, 3, 4, 5, 6]); // e.g., [3, 5, 4, 6, 2, 1]

The sample() function randomly selects one or more elements:

javascript
// Note that the result is different each time:
// Randomly select 1:
_.sample([1, 2, 3, 4, 5, 6]); // e.g., 2
// Randomly select 3:
_.sample([1, 2, 3, 4, 5, 6], 3); // e.g., [6, 1, 4]

For a complete list of functions, please refer to the Underscore documentation: Underscore.js Collections.

Collections has loaded