Array Methods
JavaScript arrays come packed with powerful built-in methods for adding, removing, searching, sorting, transforming, and combining elements. Knowing these methods deeply — and understanding which ones mutate the original vs which return a new array — is one of the most important skills in everyday JavaScript.
Mutating vs Pure Methods
The most important concept to understand before learning individual methods is whether they mutate (change) the original array or return a new array leaving the original intact. Mutating methods can cause subtle bugs when the same array is referenced in multiple places:
arr.sort(), use [...arr].sort() or ES2023's
arr.toSorted() to keep the original intact.
Adding & Removing Elements
These are the workhorse methods for modifying array contents.
They all mutate the original array, so use spread
([...arr]) or
slice() to clone first if needed:
undefined on an empty array. Classic stack operation.
push on large arrays (shifts all
existing elements).pop on large arrays.deleteCount elements
starting at start, and optionally inserts new items in their place. Returns
an array of deleted elements.const fruits = ["apple", "banana", "cherry"];
// push — add to end fruits.push("date"); console.log(fruits); // ["apple","banana","cherry","date"] // pop — remove from end const last = fruits.pop(); console.log(last); // "date" console.log(fruits); // ["apple","banana","cherry"] // unshift — add to start fruits.unshift("avocado"); console.log(fruits); // ["avocado","apple","banana","cherry"] // shift — remove from start const first = fruits.shift(); console.log(first); // "avocado" // splice — remove 1 element at index 1 const removed = fruits.splice(1, 1); console.log(removed); // ["banana"] console.log(fruits); // ["apple","cherry"] // splice — insert without removing fruits.splice(1, 0, "blueberry", "mango"); console.log(fruits); // ["apple","blueberry","mango","cherry"] // splice — replace elements fruits.splice(0, 2, "kiwi"); console.log(fruits); // ["kiwi","mango","cherry"]
Searching & Checking
These methods help you find elements or verify conditions across an array. Most return either an index, the element itself, or a boolean — and all are non-mutating:
item is found using
strict equality. Returns -1 if not found.item is
found, searching backwards. Returns -1 if not found.true if the array contains the item. Unlike
indexOf, correctly handles NaN.
undefined if none match.-1 if none match.find but searches from the end of
the array backwards.true if all elements pass the
callback test. Short-circuits on first failure.true if at least one element
passes the callback. Short-circuits on first match.const users = [ { id: 1, name: "Alice", age: 28, active: true }, { id: 2, name: "Bob", age: 17, active: false }, { id: 3, name: "Carol", age: 32, active: true } ]; // indexOf / includes — primitive search const nums = [10, 20, 30, 20]; nums.indexOf(20); // 1 (first occurrence) nums.lastIndexOf(20); // 3 (last occurrence) nums.includes(30); // true // find — first object matching predicate const adult = users.find(u => u.age >= 18); console.log(adult.name); // "Alice" // findIndex — index of first matching const idx = users.findIndex(u => !u.active); console.log(idx); // 1 (Bob) // every — all users over 16? users.every(u => u.age > 16); // true users.every(u => u.active); // false (Bob is inactive) // some — any user over 30? users.some(u => u.age > 30); // true (Carol)
Slicing, Copying & Combining
These methods extract portions of arrays or combine multiple arrays together — all without modifying the originals:
start up to (not including) end. Negative indices
count from the end. No arguments → full copy.[...a, ...b]) is the
modern equivalent.separator (default ","). The reverse of
String.split().
depth levels (default
1). Use Infinity to flatten fully regardless of depth.
.map(fn).flat(1) but more efficient.const letters = ["a", "b", "c", "d", "e"]; // slice — extract portion letters.slice(1, 4); // ["b","c","d"] letters.slice(2); // ["c","d","e"] letters.slice(-2); // ["d","e"] — last 2 letters.slice(); // shallow copy of entire array // concat — merge arrays const a = [1, 2], b = [3, 4]; a.concat(b, [5]); // [1,2,3,4,5] [...a, ...b, 5]; // [1,2,3,4,5] — modern equivalent // join — array to string ["2025", "01", "31"].join("-"); // "2025-01-31" ["H", "e", "l", "l", "o"].join(""); // "Hello" // flat — flatten nested arrays [1, [2, 3], [4, [5]]].flat(); // [1,2,3,4,[5]] — depth 1 [1, [2, [3, [4]]]].flat(Infinity); // [1,2,3,4] — fully flat // flatMap — map then flatten one level const sentences = ["Hello World", "Foo Bar"]; sentences.flatMap(s => s.split(" ")); // ["Hello","World","Foo","Bar"]
Sorting & Reversing
sort() and
reverse() mutate the original
array. ES2023 adds toSorted() and
toReversed() as pure equivalents that return
a new array:
// ❌ Default sort uses string comparison — wrong for numbers! [10, 2, 30, 4].sort(); // [10, 2, 30, 4] → "10" < "2" alphabetically! // ✅ Always provide a compare function for numbers [10, 2, 30, 4].sort((a, b) => a - b); // [2, 4, 10, 30] ascending [10, 2, 30, 4].sort((a, b) => b - a); // [30, 10, 4, 2] descending // Sort strings alphabetically (default is fine for plain strings) ["banana", "apple", "cherry"].sort(); // ["apple", "banana", "cherry"] // Sort objects by property const people = [{name:"Zara",age:25},{name:"Ali",age:30},{name:"Priya",age:22}]; people.sort((a, b) => a.age - b.age); // by age ascending people.sort((a, b) => a.name.localeCompare(b.name)); // by name // reverse — reverses in place const arr = [1, 2, 3, 4, 5]; arr.reverse(); // [5,4,3,2,1] — arr is mutated! // ✅ ES2023 — pure non-mutating versions const nums = [3, 1, 4, 1, 5]; const sorted = nums.toSorted((a, b) => a - b); // new array const reversed = nums.toReversed(); // new array console.log(nums); // [3,1,4,1,5] — unchanged! console.log(sorted); // [1,1,3,4,5] console.log(reversed); // [5,1,4,1,3]
.sort() converts elements to strings
before comparing. This makes 10 sort before 2 because
"10" < "2" lexicographically. Always pass a comparator
function when sorting numbers: (a, b) => a - b.
Full Method Quick Reference
Every essential array method at a glance — with mutation status, return value, and a one-line example:
| Method | Mutates? | Returns | Quick Example → Result |
|---|---|---|---|
| .push(x) | Yes | New length | [1,2].push(3) → 3 (len) |
| .pop() | Yes | Removed element | [1,2,3].pop() → 3 |
| .unshift(x) | Yes | New length | [2,3].unshift(1) → 3 (len) |
| .shift() | Yes | Removed element | [1,2,3].shift() → 1 |
| .splice(s,d,...) | Yes | Removed elements array | [1,2,3].splice(1,1) → [2] |
| .sort(fn?) | Yes | Same array (sorted) | [3,1,2].sort((a,b)=>a-b) → [1,2,3] |
| .reverse() | Yes | Same array (reversed) | [1,2,3].reverse() → [3,2,1] |
| .fill(v, s?, e?) | Yes | Same array (filled) | [1,2,3].fill(0,1) → [1,0,0] |
| .slice(s?,e?) | No | New array | [1,2,3,4].slice(1,3) → [2,3] |
| .concat(...arrs) | No | New array | [1].concat([2],[3]) → [1,2,3] |
| .indexOf(x) | No | Index or -1 | [10,20].indexOf(20) → 1 |
| .includes(x) | No | Boolean | [1,2,3].includes(2) → true |
| .find(fn) | No | Element or undefined | [1,5,8].find(x=>x>4) → 5 |
| .findIndex(fn) | No | Index or -1 | [1,5,8].findIndex(x=>x>4) → 1 |
| .every(fn) | No | Boolean | [2,4].every(x=>x%2===0) → true |
| .some(fn) | No | Boolean | [1,3,4].some(x=>x%2===0) → true |
| .join(sep?) | No | String | ["a","b"].join("-") → "a-b" |
| .flat(depth?) | No | New array | [1,[2,[3]]].flat() → [1,2,[3]] |
| .flatMap(fn) | No | New array | ["a b"].flatMap(s=>s.split(" ")) → ["a","b"] |
| .at(i)ES2022 | No | Element or undefined | [1,2,3].at(-1) → 3 |
| .toSorted(fn?)ES2023 | No | New sorted array | [3,1].toSorted((a,b)=>a-b) → [1,3] |
| .toReversed()ES2023 | No | New reversed array | [1,2,3].toReversed() → [3,2,1] |
| Array.isArray(v) | No | Boolean | Array.isArray([1,2]) → true |
| Array.from(iter) | No | New array | Array.from("abc") → ["a","b","c"] |
Try It — Live Editor
Experiment with array methods below. Try changing the data, chaining methods, or testing the mutating vs pure difference.
Common Patterns & Recipes
These are the real-world array utilities you'll reach for constantly in JavaScript projects:
// ── Remove duplicates ────────────────────────────────────────
const unique = [...new Set([1, 2, 2, 3, 3, 3])]; // [1,2,3]
// ── Remove item by value (non-mutating) ───────────────────────
const arr = ["a", "b", "c"];
const without = arr.filter(x => x !== "b"); // ["a","c"]
// ── Remove item by index (non-mutating) ───────────────────────
const removeAt = (arr, i) => [...arr.slice(0, i), ...arr.slice(i + 1)];
removeAt([1, 2, 3, 4], 2); // [1,2,4]
// ── Update item in array (non-mutating) ───────────────────────
const updateAt = (arr, i, val) => arr.map((x, idx) => idx === i ? val : x);
updateAt([1, 2, 3], 1, 99); // [1,99,3]
// ── Chunk array into pages ────────────────────────────────────
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
chunk([1,2,3,4,5], 2); // [[1,2],[3,4],[5]]
// ── Shuffle (Fisher-Yates) ────────────────────────────────────
function shuffle(arr) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
// ── Group array items by key ─────────────────────────────────
const people = [{name:"Alice",role:"dev"},{name:"Bob",role:"design"},{name:"Carol",role:"dev"}];
const grouped = people.reduce((acc, p) => {
(acc[p.role] ??= []).push(p.name);
return acc;
}, {});
// { dev: ["Alice","Carol"], design: ["Bob"] }[1, 2, 3].indexOf(5) return?- Array methods are either mutating (change the original: push, pop, splice, sort, reverse, fill) or pure (return new: slice, concat, flat, toSorted, toReversed).
push / popadd and remove from the end;unshift / shiftadd and remove from the start.splice(start, deleteCount, ...items)can insert, remove, or replace elements at any position.indexOf / includesfind primitives;find / findIndexfind objects using a callback predicate.everychecks if all elements pass;somechecks if at least one passes.sort()uses string comparison by default — always pass(a, b) => a - bfor numbers.- ES2023 adds
toSorted(), toReversed(), toSpliced()— non-mutating versions of the classic methods. flat(depth)flattens nested arrays;flatMap(fn)maps and flattens in one pass.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.