Skip to content

Collection Functions

A collection of utility functions for working with collections (arrays and objects).

keyBy

Creates an object composed of keys generated from the results of running each element of collection through the iteratee function. The corresponding value of each key is the last element responsible for generating the key.

// With an array of objects
const array = [
{ id: 'a1', name: 'John' },
{ id: 'b2', name: 'Jane' },
{ id: 'c3', name: 'Jack' }
];
// Using a function that returns the key
const keyedById = keyBy(array, item => item.id);
console.log(keyedById);
// {
// a1: { id: 'a1', name: 'John' },
// b2: { id: 'b2', name: 'Jane' },
// c3: { id: 'c3', name: 'Jack' }
// }
// Using a property name string
const keyedByName = keyBy(array, 'name');
console.log(keyedByName);
// {
// John: { id: 'a1', name: 'John' },
// Jane: { id: 'b2', name: 'Jane' },
// Jack: { id: 'c3', name: 'Jack' }
// }

orderBy

Creates a new array of elements sorted by multiple iteratees and respective sort orders.

// With an array of objects
const users = [
{ user: 'fred', age: 48 },
{ user: 'barney', age: 34 },
{ user: 'fred', age: 40 },
{ user: 'barney', age: 36 }
];
// Sort by user in ascending order, then by age in descending order
const result = orderBy(users, ['user', 'age'], ['asc', 'desc']);
console.log(result);
// [
// { user: 'barney', age: 36 },
// { user: 'barney', age: 34 },
// { user: 'fred', age: 48 },
// { user: 'fred', age: 40 }
// ]
// Sort by age in ascending order (default)
const ageAsc = orderBy(users, ['age']);
console.log(ageAsc);
// [
// { user: 'barney', age: 34 },
// { user: 'barney', age: 36 },
// { user: 'fred', age: 40 },
// { user: 'fred', age: 48 }
// ]
// Using functions as iteratees
const funcResult = orderBy(users,
[user => user.user, user => user.age],
['asc', 'desc']
);
console.log(funcResult);
// Same result as first example