Skip to content

Array Functions

A collection of utility functions for working with arrays.

chunk

Splits an array into chunks of the specified size.

const array = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunk(array, 3);
console.log(chunked); // [[1, 2, 3], [4, 5, 6], [7, 8]]

uniq

Removes duplicate values from an array.

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueValues = uniq(array);
console.log(uniqueValues); // [1, 2, 3, 4, 5]

uniqBy

Removes duplicate values from an array based on a computed key.

const array = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John (duplicate)' }
];
// Creating a unique list based on the id property
const uniqueById = uniqBy(array, item => item.id);
console.log(uniqueById);
// [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
// For simple values, you can use a mapping function
const numbers = [1.1, 2.5, 1.9, 2.1];
const uniqueByFloor = uniqBy(numbers, Math.floor);
console.log(uniqueByFloor); // [1.1, 2.5]

groupBy

Groups array items based on a key function.

const people = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Jack', age: 25 }
];
const grouped = groupBy(people, person => person.age);
console.log(grouped);
// {
// '25': [{ name: 'John', age: 25 }, { name: 'Jack', age: 25 }],
// '30': [{ name: 'Jane', age: 30 }]
// }

Gets the first element of an array.

const array = [1, 2, 3, 4, 5];
const first = head(array);
console.log(first); // 1
const emptyArray = [];
const emptyResult = head(emptyArray);
console.log(emptyResult); // undefined

last

Gets the last element of an array.

const array = [1, 2, 3, 4, 5];
const lastElement = last(array);
console.log(lastElement); // 5
const emptyArray = [];
const emptyResult = last(emptyArray);
console.log(emptyResult); // undefined