Book Interview →
JavaScript

JavaScript Array Methods

All the array methods you need to crack a JavaScript interview — with one-liner usage examples.

Transformation

Methods that return a new array based on a transformation function.

js
// map — transform each element
[1,2,3].map(x => x * 2);           // [2, 4, 6]

// flatMap — map then flatten one level
[1,2].flatMap(x => [x, x*2]);      // [1,2,2,4]

// filter — keep elements that pass the test
[1,2,3,4].filter(x => x % 2 === 0); // [2, 4]

Aggregation

Methods that reduce an array to a single value.

js
// reduce — accumulate into a single value
[1,2,3,4].reduce((acc, x) => acc + x, 0); // 10

// reduceRight — same but right-to-left
[[1],[2],[3]].reduceRight((acc, x) => acc.concat(x)); // [3,2,1]

Search & Test

Methods that find elements or test conditions.

js
const arr = [5, 12, 8, 130, 44];

arr.find(x => x > 10);        // 12  (first match)
arr.findIndex(x => x > 10);   // 1
arr.indexOf(8);                // 2
arr.includes(8);               // true
arr.some(x => x > 100);       // true  (at least one)
arr.every(x => x > 0);        // true  (all match)

Sorting & Ordering

Methods that reorder elements (mutate the original array).

js
[3,1,2].sort((a,b) => a - b);  // [1,2,3]  ascending
[3,1,2].sort((a,b) => b - a);  // [3,2,1]  descending
[1,2,3].reverse();             // [3,2,1]

Add / Remove

Mutating methods to add or remove elements.

js
const a = [1,2,3];
a.push(4);      // a = [1,2,3,4]   adds to end
a.pop();        // a = [1,2,3]     removes from end
a.unshift(0);   // a = [0,1,2,3]   adds to start
a.shift();      // a = [1,2,3]     removes from start
a.splice(1,1);  // a = [1,3]       removes at index 1