Method |
Returns |
Example |
Mutates |
push() |
New length |
arr.push(5) |
✅ |
pop() |
Removed element |
arr.pop() |
✅ |
shift() |
Removed element |
arr.shift() |
✅ |
unshift() |
New length |
arr.unshift(1) |
✅ |
splice() |
Removed elements |
arr.splice(1, 2) |
✅ |
slice() |
New array |
arr.slice(1, 3) |
❌ |
concat() |
New array |
arr.concat([4, 5]) |
❌ |
join() |
String |
arr.join('-') |
❌ |
- Transforms each item in the array.
- Commonly used for changing values or extracting properties.
- Returns a new array without modifying the original.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 }
];
const names = users.map(user => user.name);
const indexed = numbers.map((n, i) => `${i}: ${n}`);
- Keeps only items that match a condition.
- Useful for removing unwanted data.
- Returns a new array.
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
const users = [
{ name: 'John', age: 30, active: true },
{ name: 'Jane', age: 25, active: false },
{ name: 'Bob', age: 35, active: true }
];
const activeUsers = users.filter(user => user.active);
const adults = users.filter(user => user.age >= 18 && user.active);
- Reduces the array to a single value.
- Common for sums, maximums, grouping, and flattening.
- Can build custom output structures.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, n) => acc + n, 0);
const max = numbers.reduce((acc, n) => Math.max(acc, n), -Infinity);
const users = [
{ name: 'John', age: 30, city: 'NYC' },
{ name: 'Jane', age: 25, city: 'LA' },
{ name: 'Bob', age: 35, city: 'NYC' }
];
const groupedByCity = users.reduce((acc, user) => {
if (!acc[user.city]) acc[user.city] = [];
acc[user.city].push(user);
return acc;
}, {});
const nested = [[1, 2], [3, 4], [5]];
const flattened = nested.reduce((acc, arr) => acc.concat(arr), []);
find()
returns the first match.
findIndex()
returns the index of the first match.
- Useful when you need just one item or its position.
const users = [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Bob', age: 35 }
];
const over30 = users.find(user => user.age > 30);
const janeIndex = users.findIndex(user => user.name === 'Jane');
const notFound = users.find(user => user.age > 50) || { name: 'Not found' };
some()
checks if any item matches.
every()
checks if all items match.
- Good for quick condition checks.
const numbers = [2, 4, 6, 8, 10];
const hasOdd = numbers.some(n => n % 2 !== 0);
const allEven = numbers.every(n => n % 2 === 0);
const users = [
{ name: 'John', role: 'user' },
{ name: 'Jane', role: 'admin' },
{ name: 'Bob', role: 'user' }
];
const hasAdmin = users.some(user => user.role === 'admin');
includes()
checks if an item exists in the array.
indexOf()
returns the position or -1
if not found.
- Fast and easy lookup methods.
const fruits = ['apple', 'banana', 'orange'];
const hasApple = fruits.includes('apple');
const hasGrape = fruits.includes('grape');
const bananaIndex = fruits.indexOf('banana');
const grapeIndex = fruits.indexOf('grape');
const hasOrangeAfterIndex1 = fruits.includes('orange', 2);
- Sorts values in-place (mutates original array).
- Can sort numbers, strings, or objects with a function.
- Default sort is string-based.
const numbers = [3, 1, 4, 1, 5, 9];
const sorted = numbers.sort((a, b) => a - b);
const reverseSorted = numbers.sort((a, b) => b - a);
const names = ['Charlie', 'Alice', 'Bob'];
const sortedNames = names.sort();
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 }
];
const sortedByAge = users.sort((a, b) => a.age - b.age);
const sortedByName = users.sort((a, b) => a.name.localeCompare(b.name));
- Reverses the order of elements.
- Modifies the original array.
- Use
slice().reverse()
to keep original intact.
const numbers = [1, 2, 3, 4, 5];
const reversed = numbers.reverse();
const original = [1, 2, 3, 4, 5];
const reversedCopy = original.slice().reverse();
- Runs a function for each item in the array.
- Does not return a new array.
- Ideal for side effects like logging or external updates.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(n => console.log(n));
numbers.forEach((n, i) => console.log(`${i}: ${n}`));
let sum = 0;
numbers.forEach(n => sum += n);
- Loop that works well with arrays.
- Use
.entries()
to get index and value.
- Supports
break
and continue
.
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
console.log(num);
}
for (const [index, value] of numbers.entries()) {
console.log(`${index}: ${value}`);
}
for (const num of numbers) {
if (num > 3) break;
console.log(num);
}
- Converts things to arrays (strings, Sets).
- Can map values while creating the array.
const chars = Array.from('hello');
const unique = Array.from(new Set([1, 2, 2, 3]));
const doubled = Array.from([1, 2, 3], x => x * 2);
const range = Array.from({ length: 5 }, (_, i) => i);
- Spreads elements into a new array.
- Useful for merging, cloning, inserting, or spreading into functions.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
const copy = [...arr1];
const withInsert = [...arr1, 2.5, ...arr2];
const max = Math.max(...arr1);
- Pulls out values from arrays by position.
- Can skip or collect remaining values.
- Also useful for swapping and default values.
const numbers = [1, 2, 3, 4, 5];
const [first, second] = numbers;
const [a, , c] = numbers;
const [head, ...tail] = numbers;
const [x, y, z = 0] = [1, 2];
let a = 1, b = 2;
[a, b] = [b, a];
- Great for grouping, calculating totals, and filtering complex data.
const products = [
{ id: 1, name: 'Laptop', price: 999, category: 'electronics' },
{ id: 2, name: 'Book', price: 15, category: 'books' },
{ id: 3, name: 'Phone', price: 699, category: 'electronics' }
];
const byCategory = products.reduce((acc, product) => {
if (!acc[product.category]) acc[product.category] = [];
acc[product.category].push(product);
return acc;
}, {});
const totalByCategory = products.reduce((acc, product) => {
acc[product.category] = (acc[product.category] || 0) + product.price;
return acc;
}, {});
const expensive = products.filter(p => p.price > 500);
- Avoid unnecessary nested loops.
- Use
Set
for fast existence checks in large arrays.
const numbers = [1, 2, 3, 4, 5];
const inefficient = numbers.map(n => {
return numbers.filter(m => m < n).length;
});
const efficient = numbers.map(n => numbers.filter(m => m < n).length);
const largeArray = Array.from({ length: 10000 }, (_, i) => i);
const lookupSet = new Set(largeArray);
const hasValue = lookupSet.has(5000);