JavaScript Array Methods Cheat Sheet
The examples use const nums = [3, 1, 2]; and const users = [{ name: "Asha", age: 25 }, { name: "Ravi", age: 17 }];.
Transform and search (do not change the array)
| Method | Example | Result |
|---|---|---|
map | nums.map(n => n * 2) | [6, 2, 4] |
filter | users.filter(u => u.age >= 18) | users who are adults |
find | users.find(u => u.name === "Ravi") | the first match, or undefined |
findIndex | nums.findIndex(n => n === 2) | 2 |
some | nums.some(n => n > 2) | true |
every | nums.every(n => n > 0) | true |
includes | nums.includes(1) | true |
indexOf | nums.indexOf(2) | 2 |
slice | nums.slice(0, 2) | [3, 1] |
concat | nums.concat([9]) | [3, 1, 2, 9] |
join | nums.join("-") | "3-1-2" |
flat | [[1], [2, 3]].flat() | [1, 2, 3] |
Reduce
const total = nums.reduce((sum, n) => sum + n, 0); // 6
const byName = users.reduce((acc, u) => ({ ...acc, [u.name]: u.age }), {});
The second argument is the starting value. Always give one.
Change the original array
| Method | What it does |
|---|---|
push(x) pop() | Add or remove at the end |
unshift(x) shift() | Add or remove at the start |
splice(i, n) | Remove n items from index i |
sort() | Sorts in place |
reverse() | Reverses in place |
Sorting
nums.sort(); // sorts as text by default: [1, 10, 2]
nums.sort((a, b) => a - b); // numbers, small to large
users.sort((a, b) => a.name.localeCompare(b.name));
const copy = [...nums].sort((a, b) => a - b); // keep the original
Handy patterns
const unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]
const [first, ...rest] = nums; // destructuring
Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2]
Newer methods such as toSorted and toReversed return a copy instead of changing the array, but check browser support first.