JavaScript Array Methods Guide
Complete reference for JavaScript array methods organized by use case. Learn when to use which method and understand their performance implications.
Transforming Arrays
Create new arrays by transforming existing elements.
map()
Creates a new array by applying a function to each element.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8]
const users = [
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Jane', lastName: 'Smith' }
];
const fullNames = users.map(u => `${u.firstName} ${u.lastName}`);
// ['John Doe', 'Jane Smith']
Returns: New array (same length as original)
Mutates: No
Use when: You need to transform every element
flatMap()
Maps and flattens the result by one level.
const sentences = ['Hello world', 'How are you'];
const words = sentences.flatMap(s => s.split(' '));
// ['Hello', 'world', 'How', 'are', 'you']
// More efficient than map + flat
// sentences.map(s => s.split(' ')).flat();
Returns: New flattened array
Mutates: No
Use when: Mapping produces arrays that need flattening
flat()
Flattens nested arrays to specified depth.
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]]
nested.flat(2); // [1, 2, 3, 4, 5, 6]
nested.flat(Infinity); // Flattens all levels
Returns: New flattened array
Mutates: No
Use when: Working with nested array structures
Filtering Arrays
Create subsets of arrays based on conditions.
filter()
Creates array with elements that pass a test.
const numbers = [1, 2, 3, 4, 5, 6];
const even = numbers.filter(n => n % 2 === 0);
// [2, 4, 6]
const products = [
{ name: 'Laptop', price: 999 },
{ name: 'Mouse', price: 29 },
{ name: 'Keyboard', price: 79 }
];
const affordable = products.filter(p => p.price < 100);
// [{ name: 'Mouse', price: 29 }, { name: 'Keyboard', price: 79 }]
Returns: New array (0 to original length)
Mutates: No
Use when: You need a subset based on a condition
slice()
Extracts a section of an array.
const items = ['a', 'b', 'c', 'd', 'e'];
items.slice(2); // ['c', 'd', 'e'] - from index 2 to end
items.slice(1, 4); // ['b', 'c', 'd'] - from index 1 to 4 (exclusive)
items.slice(-2); // ['d', 'e'] - last 2 items
items.slice(); // shallow copy of array
Returns: New array
Mutates: No
Use when: You need a portion of the array
Searching Arrays
Find elements or their positions in arrays.
find()
Returns the first element that satisfies the condition.
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
const user = users.find(u => u.id === 2);
// { id: 2, name: 'Jane' }
const missing = users.find(u => u.id === 99);
// undefined
Returns: First matching element or undefined
Use when: You need the first matching element
findIndex()
Returns index of first element that satisfies the condition.
const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(n => n > 25);
// 2
const notFound = numbers.findIndex(n => n > 100);
// -1
Returns: Index or -1
Use when: You need the position of an element
findLast() & findLastIndex()
ES2023Like find() and findIndex(), but search from the end.
const items = [1, 2, 3, 4, 5];
const last = items.findLast(n => n > 2);
// 5 (searches from end)
const lastIndex = items.findLastIndex(n => n > 2);
// 4 (index of 5)
indexOf() & lastIndexOf()
Find index of a specific value.
const fruits = ['apple', 'banana', 'apple', 'orange'];
fruits.indexOf('apple'); // 0 (first occurrence)
fruits.lastIndexOf('apple'); // 2 (last occurrence)
fruits.indexOf('grape'); // -1 (not found)
// Can start from specific index
fruits.indexOf('apple', 1); // 2 (starts from index 1)
Returns: Index or -1
Use when: Searching for primitive values by equality
includes()
Checks if array contains a value.
const numbers = [1, 2, 3, 4, 5];
numbers.includes(3); // true
numbers.includes(10); // false
numbers.includes(2, 3); // false (starts from index 3)
// Works with NaN (unlike indexOf)
[1, 2, NaN].includes(NaN); // true
Returns: Boolean
Use when: You just need to know if value exists
Sorting & Reordering
Change the order of array elements.
sort()
MutatesSorts array in place. Default is string comparison.
// String sorting (default)
const fruits = ['banana', 'apple', 'cherry'];
fruits.sort();
// ['apple', 'banana', 'cherry']
// Number sorting (need comparator!)
const numbers = [10, 5, 40, 25];
numbers.sort((a, b) => a - b); // Ascending
// [5, 10, 25, 40]
numbers.sort((a, b) => b - a); // Descending
// [40, 25, 10, 5]
// Object sorting
const users = [
{ name: 'Charlie', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
users.sort((a, b) => a.age - b.age);
// Sorted by age ascending
Mutates: Yes
Returns: The sorted array (same reference)
Tip: Use .slice().sort() to avoid mutation
toSorted()
ES2023Like sort() but returns new array.
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.toSorted((a, b) => a - b);
// numbers: [3, 1, 4, 1, 5] (unchanged)
// sorted: [1, 1, 3, 4, 5]
Mutates: No
reverse()
MutatesReverses array in place.
const numbers = [1, 2, 3, 4];
numbers.reverse();
// [4, 3, 2, 1]
Mutates: Yes
toReversed()
ES2023Like reverse() but returns new array.
const numbers = [1, 2, 3, 4];
const reversed = numbers.toReversed();
// numbers: [1, 2, 3, 4] (unchanged)
// reversed: [4, 3, 2, 1]
Mutates: No
Aggregating Data
Reduce arrays to single values.
reduce()
Reduces array to a single value.
// Sum
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15
// Max value
const max = numbers.reduce((acc, n) => Math.max(acc, n));
// 5
// Group by property
const items = [
{ category: 'fruit', name: 'apple' },
{ category: 'vegetable', name: 'carrot' },
{ category: 'fruit', name: 'banana' }
];
const grouped = items.reduce((acc, item) => {
if (!acc[item.category]) acc[item.category] = [];
acc[item.category].push(item.name);
return acc;
}, {});
// { fruit: ['apple', 'banana'], vegetable: ['carrot'] }
// Count occurrences
const letters = ['a', 'b', 'a', 'c', 'b', 'a'];
const counts = letters.reduce((acc, letter) => {
acc[letter] = (acc[letter] || 0) + 1;
return acc;
}, {});
// { a: 3, b: 2, c: 1 }
Returns: Any value
Use when: You need to transform array into a single value
reduceRight()
Like reduce() but iterates from right to left.
const items = ['a', 'b', 'c'];
const result = items.reduceRight((acc, item) => acc + item);
// 'cba'
join()
Joins array elements into a string.
const words = ['Hello', 'world'];
words.join(' '); // 'Hello world'
words.join(', '); // 'Hello, world'
words.join(''); // 'Helloworld'
const path = ['users', 'john', 'documents'];
path.join('/'); // 'users/john/documents'
Returns: String
Testing Arrays
Check if array elements meet conditions.
every()
Tests if ALL elements pass the condition.
const numbers = [2, 4, 6, 8];
numbers.every(n => n % 2 === 0); // true (all even)
const ages = [18, 21, 25, 30];
const allAdults = ages.every(age => age >= 18); // true
const mixed = [2, 4, 5, 8];
mixed.every(n => n % 2 === 0); // false (5 is odd)
Returns: Boolean
Use when: All elements must pass test
some()
Tests if ANY element passes the condition.
const numbers = [1, 3, 5, 8];
numbers.some(n => n % 2 === 0); // true (8 is even)
const scores = [45, 67, 89, 92];
const anyFailed = scores.some(s => s < 50); // true
const allPass = [75, 80, 85];
allPass.some(s => s < 50); // false
Returns: Boolean
Use when: At least one element must pass test
Array.isArray()
Checks if value is an array.
Array.isArray([1, 2, 3]); // true
Array.isArray('hello'); // false
Array.isArray({ length: 0 }); // false
Array.isArray(null); // false
Adding & Removing Elements
Modify array contents.
push()
MutatesAdds elements to the end.
const fruits = ['apple', 'banana'];
fruits.push('cherry'); // Returns: 3 (new length)
// ['apple', 'banana', 'cherry']
fruits.push('date', 'elderberry'); // Can add multiple
// ['apple', 'banana', 'cherry', 'date', 'elderberry']
pop()
MutatesRemoves and returns last element.
const fruits = ['apple', 'banana', 'cherry'];
const last = fruits.pop(); // Returns: 'cherry'
// fruits: ['apple', 'banana']
unshift()
MutatesAdds elements to the beginning.
const fruits = ['banana', 'cherry'];
fruits.unshift('apple'); // Returns: 3 (new length)
// ['apple', 'banana', 'cherry']
shift()
MutatesRemoves and returns first element.
const fruits = ['apple', 'banana', 'cherry'];
const first = fruits.shift(); // Returns: 'apple'
// fruits: ['banana', 'cherry']
splice()
MutatesAdds/removes elements at any position.
const items = ['a', 'b', 'c', 'd', 'e'];
// Remove 2 elements from index 1
items.splice(1, 2);
// Removed: ['b', 'c']
// items: ['a', 'd', 'e']
// Insert elements at index 1
items.splice(1, 0, 'x', 'y');
// items: ['a', 'x', 'y', 'd', 'e']
// Replace elements
items.splice(1, 2, 'new');
// Removed: ['x', 'y']
// items: ['a', 'new', 'd', 'e']
toSpliced()
ES2023Like splice() but returns new array.
const items = ['a', 'b', 'c', 'd'];
const newItems = items.toSpliced(1, 2, 'x');
// items: ['a', 'b', 'c', 'd'] (unchanged)
// newItems: ['a', 'x', 'd']
with()
ES2023Returns new array with element at index replaced.
const items = ['a', 'b', 'c', 'd'];
const newItems = items.with(2, 'X');
// items: ['a', 'b', 'c', 'd'] (unchanged)
// newItems: ['a', 'b', 'X', 'd']
Iterating Arrays
Loop through array elements.
forEach()
Executes function for each element.
const numbers = [1, 2, 3, 4];
numbers.forEach((num, index) => {
console.log(`${index}: ${num}`);
});
// 0: 1
// 1: 2
// 2: 3
// 3: 4
// Cannot break or return early
// Use for...of if you need to break
Returns: undefined
Use when: You need to execute side effects for each element
entries(), keys(), values()
Returns iterator for indices, keys, or values.
const fruits = ['apple', 'banana', 'cherry'];
// entries() - [index, value] pairs
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit);
}
// keys() - indices only
for (const index of fruits.keys()) {
console.log(index); // 0, 1, 2
}
// values() - values only
for (const fruit of fruits.values()) {
console.log(fruit); // 'apple', 'banana', 'cherry'
}
Combining Arrays
Merge and create new arrays.
concat()
Merges arrays into new array.
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
const combined = arr1.concat(arr2, arr3);
// [1, 2, 3, 4, 5, 6]
// Can add individual elements
arr1.concat(2, 3, arr2);
// [1, 2, 2, 3, 3, 4]
Modern alternative: Spread operator [...arr1, ...arr2]
Spread Operator
Modern way to combine arrays.
const arr1 = [1, 2];
const arr2 = [3, 4];
// Combine arrays
const combined = [...arr1, ...arr2];
// [1, 2, 3, 4]
// Copy array
const copy = [...arr1];
// Add elements
const extended = [...arr1, 3, 4, ...arr2];
// [1, 2, 3, 4, 3, 4]
// Array from arguments
function sum(...numbers) {
return numbers.reduce((a, b) => a + b);
}
sum(1, 2, 3, 4); // 10
Array.from()
Creates array from iterable or array-like object.
// From string
Array.from('hello');
// ['h', 'e', 'l', 'l', 'o']
// From Set
Array.from(new Set([1, 2, 2, 3]));
// [1, 2, 3]
// With mapping function
Array.from([1, 2, 3], x => x * 2);
// [2, 4, 6]
// Create range
Array.from({ length: 5 }, (_, i) => i);
// [0, 1, 2, 3, 4]
Array.of()
Creates array from arguments.
Array.of(1, 2, 3); // [1, 2, 3]
Array.of(7); // [7]
// Compare with Array constructor
Array(7); // [ empty x 7 ]
Array.of(7); // [7]
Performance Tips:
- Methods like
map(),filter(), andreduce()create new arrays - chain wisely forloops are fastest for simple iterationssome()andevery()short-circuit (stop early)find()is faster thanfilter()[0]- Avoid mutating methods in functional code (use
toSorted(),toReversed(), etc.)