JavaScript Array Functions
JavaScript has several built-in functions that can be used to manipulate arrays. Some of the commonly used array functions are listed below.
forEach()
Definition: The forEach() method executes a provided function once for each array element.
Parameters: callbackFn(element, index, array).
Returns: undefined.
It is commonly used for iterating over an array.
const nums = [1, 2, 3];
nums.forEach(n => console.log(n)); // 1 2 3
pop()
Definition: The pop() method removes the last element from an array.
Parameters: none.
Returns: the removed element.
This method changes the length of the array.
const nums = [1, 2, 3];
const removed = nums.pop();
console.log(nums); // [1, 2]
console.log(removed); // 3
push()
Definition: The push() method adds the specified element(s) to the end of an array.
Parameters: element(s) to be inserted.
Returns: new length of the array.
This method changes the length of the array.
const nums = [1, 2, 3];
nums.push(4);
console.log(nums); // [1, 2, 3, 4]
console.log(nums.push(5, 6, 7)); // 7
console.log(nums); // [1, 2, 3, 4, 5, 6, 7]
const length = nums.push([0, -1]);
console.log(nums) // [1, 2, 3, 4, 5, 6, 7, [0, -1]];
console.log(length); // 8
shift()
Definition: The shift() method removes the first element from an array.
Parameters: none.
Returns: the removed element.
This method changes the length of the array.
const nums = [1, 2, 3];
const removed = nums.shift();
console.log(nums); // [2, 3]
console.log(removed); // 1
unshift()
Definition: The unshift() method adds the specified element(s) to the beginning of an array.
Parameters: element(s) to be inserted.
Returns: new length of the array.
This method changes the length of the array.
const nums = [1, 2, 3];
console.log(nums.unshift(4, 5)); // 5
console.log(nums); // [4, 5, 1, 2, 3]
concat()
Definition: The concat() method is used to merge two or more arrays.
Parameters: array(s) to be merged.
Returns: the merged array.
This method doesn't mutate the original array(s).
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
arr1.concat(arr2); // [1, 2, 3, 4]
arr1.concat(arr2, arr3); // [1, 2, 3, 4, 5, 6]
console.log({ arr1, arr2, arr3 }); // {arr1: [1, 2], arr2: [3, 4], arr3: [5, 6]}
join()
Definition: The join() method is used to create a new string by concatenating all the elements in an array.
Parameters: separator. The default separator is a comma (,).
Returns: the new string formed after concatenation.
If the array has only one item, then that item is returned without using the separator.
const arr = ['fire', 'water'];
arr.join(); // fire,water
arr.join(' and '); // fire and water
['fire'].join(); // fire
// reversing a string
const s = 'apple';
s.split('').reverse().join(''); // elppa
reverse()
Definition: The reverse() method reverses an array.
Parameters: none.
Returns: the reference to the same array, now reversed.
This method mutates the original array.
const arr = [1, 2, 3];
const reverse = arr.reverse();
console.log(arr); // [3, 2, 1]
console.log(reverse); // [3, 2, 1]
toReversed()
Definition: The toReversed() method reverses an array, without changing the original array.
Parameters: none.
Returns: a new reversed array.
This method doesn't mutate the original array.
const arr = [1, 2, 3];
const reverse = arr.toReversed();
console.log(arr); // [1, 2, 3]
console.log(reverse); // [3, 2, 1]
filter()
Definition: The filter() method is used to create a new array containing elements that meet a specified condition.
Parameters: callbackFn(element, index, array).
Returns: a new filtered array.
This method doesn't mutate the original array.
const nums = [8, 6, 9, 4, 2, 1, 3, 10, 12];
const filtered = nums.filter((num, index) => {
return num % 2 === 0 && index % 2 !== 0
});
console.log(filtered); // [6, 4, 10]
console.log(nums); // [8, 6, 9, 4, 2, 1, 3, 10, 12]
map()
Definition: The map() method is used to create a new array populated with the results of calling the provided function on every element in the calling array.
Parameters: callbackFn(element, index, array).
Returns: a new array.
This method doesn't mutate the original array.
const nums = [1, 2];
const square = nums.map(num => num * num);
console.log(square); // [1, 4]
console.log(nums); // [1, 2]
reduce()
Definition: The reduce() method is used to reduce an array to a single value by applying a callback function to each array element, and passing in the return value from the calculation on the preceding element to this callback function.
Parameters: callbackFn(accumulator, currentValue, index, array), initialValue.
Returns: accumulated value obtained after reducing the array.
This method doesn't mutate the original array. If an initialValue is not provided, the first element of the array is used as the initialValue, and the iteration will start from the second element.
const nums = [1, 2, 3];
// with initialValue
nums.reduce((total, n) => total + (n * 2), 0); // 12
// without initialValue
nums.reduce((total, n) => total + (n * 2)); // 11
In the above example, without the initial value, 1 is taken as the initial value, and the result is 1 + (4 + 6) instead of 0 + (2 + 4 + 6).
reduceRight()
Definition: The reduceRight() method is similar to reduce() method, but here the execution starts from the right side.
Parameters: callbackFn(accumulator, currentValue, index, array), initialValue.
Returns: accumulated value obtained after reducing the array.
This method doesn't mutate the original array. If an initialValue is not provided, the last element of the array is used as the initialValue, and the iteration will start from the second last element.
const nums = [1, 2, 0, 3, 4];
// reduceRight
nums.reduceRight((sum, n) => {
return n === 0 ? 0 : sum + n;
}, 0); // 3
// reduce
nums.reduce((sum, n) => {
return n === 0 ? 0 : sum + n;
}, 0); // 7
sort()
Definition: The sort() method sorts the elements of an array as string(s). The default sort order is ascending.
Parameters: compareFn(firstElement, secondElement).
Returns: reference to the same array, now sorted.
This method mutates the original array.
const arr1 = [1, 11, 12, 20, 21245, 3];
const arr2 = ['a', 'bab', 'aa', 'ab', 'aab', 'baa', 'bc'];
// default
arr1.sort() // [1, 11, 12, 20, 21245, 3];
// ascending
arr1.sort((a, b) => a - b); // [1, 3, 11, 12, 20, 21245]
// descending
arr1.sort((a, b) => b - a); // [21245, 20, 12, 11, 3, 1]
arr2.sort(); // ['a', 'aa', 'aab', 'ab', 'baa', 'bab', 'bc']
toSorted()
Definition: The toSorted() method is similar to sorted() method, the only difference being that it doesn't mutate the original array.
Parameters: compareFn(firstElement, secondElement).
Returns: reference to the same array, now sorted.
This method doesn't mutate the original array.
const arr = [1, 2 , 0];
const sorted = arr.toSorted((a, b) => a - b);
console.log(sorted); // [0, 1, 2]
console.log(arr); // [1, 2, 0]
find()
Definition: The find() method is used to find the first element in an array that satisfies the provided testing function.
Parameters: callbackFn(element, index, array).
Returns: first element that matches the given condition or undefined.
const nums = [1, 2, 3, 4];
nums.find(n => n % 2 === 0); // 2
nums.find(n => n % 5 === 0); // undefined
findIndex()
Definition: The findIndex() method is used to find the index of the first element in an array that satisfies the provided testing function.
Parameters: callbackFn(element, index, array).
Returns: index of first element that matches the given condition or -1.
const nums = [1, 2, 3, 4];
nums.findIndex(n => n % 2 === 0); // 1
nums.findIndex(n => n % 5 === 0); // -1
indexOf()
Definition: The indexOf() method is similar to findIndex(), but it checks each element for equality with the value instead of using a testing function.
Parameters: (searchElement, fromIndex).
Returns: index of first element that matches the given search value or -1.
If fromIndex < 0, fromIndex + array.length is used. But the array is still searched from front to back. If fromIndex < -array.length or the fromIndex is omitted, 0 is used as fromIndex and the entire array is searched.
const nums = [1, 2 , 3, 1];
nums.indexOf(1); // 0
nums.indexOf(1, 1); // 3
nums.indexOf(0); // -1
nums.indexOf(1, 4); -1
nums.indexOf(1, -1); // 3,
nums.indexOf(1, -4); // 0
nums.indexOf(1, -5); // 0
findLast()
Definition: The findLast() method is used to find the last element in an array that satisfies the provided testing function.
Parameters: callbackFn(element, index, array).
Returns: last element that matches the given condition or undefined.
Technically, this method traverses the array in reverse order and returns the first element that matches the provided function.
const nums = [1, 2, 3, 4];
nums.findLast(n => n % 2 === 0); // 4
nums.findLast(n => n % 5 === 0); // undefined
findLastIndex()
Definition: The findLastIndex() method is used to find the index of the last element in an array that satisfies the provided testing function.
Parameters: callbackFn(element, index, array).
Returns: index of last element that matches the given condition or -1.
Technically, this method traverses the array in reverse order and returns the index of first element that matches the provided function.
const nums = [1, 2, 3, 4];
nums.findLastIndex(n => n % 2 === 0); // 3
nums.findLastIndex(n => n % 5 === 0); // -1
lastIndexOf()
Definition: The lastIndexOf() method is similar to lastIndex(), but it checks each element for equality with the value instead of using a testing function.
Parameters: (searchElement, fromIndex).
Returns: index of last element that matches the given search value or -1.
If fromIndex < 0, fromIndex + array.length is used. If fromIndex < -array.length, the array is not searched and-1 is returned. If fromIndex >= array.length or the fromIndex is omitted, array.length - 1 is used as the fromIndex and the entire array is searched.
Technically, this method traverses the array in reverse order and returns the index of the first element that matches the searchElement.
const nums = [1, 2 , 3, 1];
nums.lastIndexOf(1); // 3
nums.lastIndexOf(1, 1); // 0
nums.lastIndexOf(0); // -1
nums.lastIndexOf(1, 3); // 3
nums.lastIndexOf(1, -4); // 0
nums.lastIndexOf(1, 10); // 3,
nums.lastIndexOf(1, -5); // -1
some()
Definition: The some() method is used to check if one or more elements in the array pass the provided function.
Parameters: callbackFn(element, index, array).
Returns: true if at least one element in the array passes the provided function, else false.
This method doesn't mutate the original array.
const nums = [3,5,9];
nums.some(n => n % 2 === 0); // false
nums.some(n => n % 3 === 0); // true
every()
Definition: The every() method is used to check if every element in the array passes the provided function.
Parameters: callbackFn(element, index, array).
Returns: true if all the element in the array passes the provided function, else false.
This method doesn't mutate the original array.
const nums = [5, 10, 15];
nums.every(n => n % 5 === 0); // true
nums.every(n => n % 3 === 0); // false
includes()
Definition: The includes() method is used to check if an array contains the given element.
Parameters: (searchElement, fromIndex).
Returns: true if array contains the searchElement, else false.
Array is always checked from the left side.
const nums = [1, 2, 3];
nums.includes(1); // true
nums.includes(1, 1); // false
nums.includes(1, -1); // false
nums.includes(1, -3); // true
nums.includes(1, -10); // true
fill()
Definition: The fill() method is used to modify an array in a given range.
Parameters: (value, start, end).
Returns: the modified array.
This method mutates the original array. Start is inclusive , and end is exclusive.
const arr = new Array(5);
arr.fill(0); // [0, 0, 0, 0, 0]
arr.fill(1, 2); // [0, 0, 1, 1, 1]
arr.fill(2, 3, 4); // [0, 0, 1, 2, 1]
arr.fill(-1, 1, 1); // [0, 0, 1, 2, 1]
slice()
Definition: The slice() method is used to create a shallow copy of an array in a given range.
Parameters: (start, end).
Returns: shallow copy of the given array in the given range.
This method doesn't mutate the original array. Start is inclusive , and end is exclusive.
const arr = [1, 2, 3, 4, 5];
arr.slice(); // [1, 2, 3, 4, 5]
arr.slice(2); // [3, 4, 5]
arr.slice(1, -1); // [2, 3, 4]
arr.slice(0, 3); // [1, 2, 3]
arr.slice(-2); // [4, 5]
splice()
Definition: The splice() method is used to add, remove, or replace element(s) in an array.
Parameters: (start, deleteCount, n items to be added).
Returns: an array containing the deleted elements.
This method mutates the original array.
const arr = [1, 2, 3, 4, 5];
// adding elements
arr.splice(0, 0, -1, 0); // return: [], arr: [-1, 0, 1, 2, 3, 4, 5]
arr.splice(-2, 0, -3); // return: [], arr: [-1, 0, 1, 2, 3, -3, 4, 5]
// replacing elements
arr.splice(0, 1, 5); // return: [-1], arr: [5, 0, 1, 2, 3, -3, 4, 5]
arr.splice(3, 2, 0, 0, 0); // return: [2, 3], arr: [5, 0, 1, 0, 0, 0, -3, 4, 5]
arr.splice(-1, 2, -5); // return: [5], arr: [5, 0, 1, 0, 0, 0, -3, 4, -5]
// removing elements
arr.splice(0, 5); // return: [5, 0, 1, 0, 0], arr: [0, -3, 4, -5]
arr.splice(0, arr.length); // return: [0, -3, 4, -5], arr: []
toSpliced()
Definition: The toSpliced() method is similar to splice(), the only difference being that it doesn't mutate the original array.
Parameters: (start, deleteCount, n items to be added).
Returns: an array containing the deleted elements.
This method doesn't mutate the original array.
const arr = [1, 2, 3];
arr.toSpliced(0, 0, 0); // return: [0, 1, 2, 3], arr: [1, 2, 3]
with()
Definition: The with() method is used to change an element in an array at a given index.
Parameters: (index, value).
Returns: a new array with the element at index replaced with value.
This method doesn't mutate the original array. An exception is thrown if index >= array.length or index < -array.length
const arr = [1, 2, 3, 4];
arr.with(0, -1); // [-1, 2, 3, 4];
arr.with(-4, -4); // [-4, 2, 3, 4];
arr.with(4, 4); // error
arr.with(-5, -1); // error
at()
Definition: The at() method is used to fetch an array element at a given index.
Parameters: (index).
Returns: value of array element at given index if index is valid, else undefined.
const arr = [1, 2, 3];
arr.at(0); // 1
arr.at(-2); // 2
arr.at(3); // undefined
arr.at(-4); // undefined
copyWithin()
Definition: The copyWithin() method shallow copies a part of an array to another location in the same array, without modifying the array's length.
Parameters: (target, start, end).
Returns: the modified array.
This method mutates the original array.
const arr = [1, 2, 3, 4];
arr.copyWithin(1, 0, 1); // [1, 1, 3, 4]
arr.copyWithin(0, 1, 3); // [1, 3, 3, 4]
arr.copyWithin(3, 0); // [1, 3, 3, 1]
arr.copyWithin(-3, 0); // [1, 1, 3, 3]
flat()
Definition: The flat() method is used to flat a nested array upto a specified. depth.
Parameters: (depth).
Returns: the new array with the sub-array elements concatenated into it.
This method doesn't mutate the original array. The default depth is 1.
const arr = [1, 2, [3, 4, [5, 6, [7]]], 8];
arr.flat(); // [1, 2, 3, 4, [5, 6, [7]], 8]
arr.flat(2); // [1, 2, 3, 4, 5, 6, [7], 8]
arr.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8]
flatMap()
Definition: The flatMap() method is a combination of flat & map methods. First the map method is applied, followed by the flat method with a depth of 1.
Parameters: callbackFn(element, index, array).
Returns: the new modified array.
This method doesn't mutate the original array. It is slightly more efficeint than calling map & flat methods separately.
const arr = [1, 2, [3, 4], 5];
arr.flatMap((ele) => Array.isArray(ele) === false ? ele * 2 : ele); // [2, 4, 3, 4, 10]
isArray()
Definition: The isArray() method is used to check whether the passed value is an array or not.
Parameters: (value).
Returns: true if value is an array, else false.
Array.isArray([1, 2]); // true
Array.isArray([]); // true
Array.isArray(1); // false
from()
Definition: The from() method is used to create a new, shallow copied array instance from an iterable or array-like object.
Parameters: (arrayLike, mapFn(element, index)).
Returns: a new array instance.
Array.from('abc'); // ['a', 'b', 'c']
Array.from([1, 2, 3], (n) => n * 2); // [2, 4, 6]
Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2]
// from map
const map = new Map([[1, 'a'], [2, 'b']]);
Array.from(map.keys()); // [1, 2]
Array.from(map.values()); // ['a', 'b']
of()
Definition: The of() method, shallow copied array instance from n arguments, regardless of number or type of arguments.
Parameters: (n elements).
Returns: a new array instance.
Array.of(1); // [1]
Array.of(1, 2, 3); // [1, 2, 3]
// Array
Array(1); // [empty]
Cheat Sheet
[1, 2, 3].forEach(n => console.log(n)); // 1 2 3
[1, 2, 3].pop(); // 3, arr: [1, 2]
[1, 2, 3].push(4); // 4, arr: [1, 2, 3, 4]
[1, 2, 3].shift(); // 1, arr: [2, 3]
[1, 2, 3].unshift(0); // 4, arr: [0, 1, 2, 3]
[1, 2].concat([3]); // [1, 2, 3]
[1, 2].join(' and '); // '1 and 2'
[1, 2, 3].reverse(); // [3, 2, 1], arr: [3, 2, 1]
[1, 2, 3].toReversed(); // [3, 2, 1], arr: [1, 2, 3]
['', false, null, undefined, 'a', 5, true].filter(Boolean); // ['a', 5, true]
[1, 2, 3].map(n => n * 2); // [2, 4, 6]
[1, 2, 0, 4].reduce((total, n) => n === 0 ? 0 : total + n, 0); // 4
[1, 2, 0, 3].reduceRight((total, n) => n === 0 ? 0 : total + n, 0); // 3
[1, 2, 11, 3].sort(); // [1, 11, 2, 3], arr: [1, 11, 2, 3]
[1, 2, 11, 3].toSorted(); // [1, 11, 2, 3], arr: [1, 2, 11, 3]
[1, 2, 3].find(n => n % 2 === 0); // 2
[1, 2, 3].findIndex(n => n % 2 === 0); // 1
[1, 2, 3, 1].indexOf(1, -2); // 3
[1, 2, 3].findLast(n => n % 2 !== 0); // 3
[1, 2, 3].findLastIndex(n => n % 2 !== 0); // 2
[1, 2, 3, 1].lastIndexOf(1, -2); // 0
[1, 2, 3].some(n => n % 2 === 0); // true
[1, 2, 3].every(n => n % 2 === 0); // false
[1, 2, 3].includes(1, 1); // false
[1, 2, 3].fill(0, 1, 2); // [1, 0, 3]
[1, 2, 3].slice(1); // [2, 3]
[1, 2, 3].splice(1, 1, 0); // [2], arr: [1, 0, 3]
[1, 2, 3].toSpliced(1, 1, 0); // [2], arr: [1, 2, 3]
[1, 2, 3].with(1, 0); // [1, 0, 3]
[1, 2, 3].at(-2); 2
[1, 2, 3].copyWithin(1, 0); // [1, 1, 2]
[1, 2, [3, [4]]].flat(Infinity); // [1, 2, 3, 4]
[1, 2, [3, 4], 5].flatMap(n => n * 2); // [2, 4, NaN, 10]
Array.isArray([1, 2]); // true
Array.from('abc'); // ['a', 'b', 'c']
Array.of(1, 2, 3); // [1, 2, 3]