JavaScript arrays come with powerful built-in methods that make data manipulation easy. This guide covers all the essential array methods you need to know.
Creating Arrays #
// Array literal
const arr1 = [1, 2, 3, 4, 5];
// Array constructor
const arr2 = new Array(5); // Creates array with 5 empty slots
const arr3 = new Array(1, 2, 3); // Creates [1, 2, 3]
// Array.of
const arr4 = Array.of(5); // [5] - not an array of length 5
// Array.from
const arr5 = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
const arr6 = Array.from({length: 5}, (_, i) => i); // [0, 1, 2, 3, 4]
Adding and Removing Elements #
push() - Add to End #
const arr = [1, 2, 3];
arr.push(4); // Returns 4 (new length)
console.log(arr); // [1, 2, 3, 4]
// Multiple elements
arr.push(5, 6, 7);
console.log(arr); // [1, 2, 3, 4, 5, 6, 7]
pop() - Remove from End #
const arr = [1, 2, 3, 4];
const last = arr.pop(); // Returns 4
console.log(arr); // [1, 2, 3]
unshift() - Add to Beginning #
const arr = [2, 3, 4];
arr.unshift(1); // Returns 4 (new length)
console.log(arr); // [1, 2, 3, 4]
arr.unshift(-1, 0);
console.log(arr); // [-1, 0, 1, 2, 3, 4]
shift() - Remove from Beginning #
const arr = [1, 2, 3, 4];
const first = arr.shift(); // Returns 1
console.log(arr); // [2, 3, 4]
Iterating Arrays #
forEach() - Execute Function on Each Element #
const arr = [1, 2, 3, 4];
arr.forEach((item, index, array) => {
console.log(`Index ${index}: ${item}`);
});
// Index 0: 1
// Index 1: 2
// Index 2: 3
// Index 3: 4
// Cannot break or return early
map() - Transform Each Element #
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
const objects = numbers.map(n => ({ value: n }));
console.log(objects); // [{value: 1}, {value: 2}, {value: 3}, {value: 4}]
// With index
const indexed = numbers.map((n, i) => `${i}: ${n}`);
console.log(indexed); // ['0: 1', '1: 2', '2: 3', '3: 4']
filter() - Keep Elements That Pass Test #
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]
const greaterThanThree = numbers.filter(n => n > 3);
console.log(greaterThanThree); // [4, 5, 6]
// Remove falsy values
const mixed = [0, 1, false, 2, '', 3];
const truthy = mixed.filter(Boolean);
console.log(truthy); // [1, 2, 3]
reduce() - Reduce to Single Value #
const numbers = [1, 2, 3, 4, 5];
// Sum
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15
// Product
const product = numbers.reduce((acc, n) => acc * n, 1);
console.log(product); // 120
// Max value
const max = numbers.reduce((max, n) => n > max ? n : max);
console.log(max); // 5
// Group by property
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 25 }
];
const byAge = people.reduce((acc, person) => {
if (!acc[person.age]) {
acc[person.age] = [];
}
acc[person.age].push(person);
return acc;
}, {});
console.log(byAge);
// {
// 25: [{name: 'Alice', age: 25}, {name: 'Charlie', age: 25}],
// 30: [{name: 'Bob', age: 30}]
// }
reduceRight() - Reduce from Right to Left #
const arr = ['a', 'b', 'c'];
const result = arr.reduceRight((acc, char) => acc + char);
console.log(result); // 'cba'
Searching Arrays #
find() - First Element That Passes Test #
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const user = users.find(u => u.id === 2);
console.log(user); // {id: 2, name: 'Bob'}
const notFound = users.find(u => u.id === 99);
console.log(notFound); // undefined
findIndex() - Index of First Match #
const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(n => n > 25);
console.log(index); // 2
const notFound = numbers.findIndex(n => n > 100);
console.log(notFound); // -1
findLast() and findLastIndex() #
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const last = numbers.findLast(n => n === 4);
console.log(last); // 4
const lastIndex = numbers.findLastIndex(n => n === 4);
console.log(lastIndex); // 5
indexOf() - First Index of Value #
const arr = [1, 2, 3, 2, 1];
console.log(arr.indexOf(2)); // 1
console.log(arr.indexOf(2, 2)); // 3 (start from index 2)
console.log(arr.indexOf(99)); // -1
lastIndexOf() - Last Index of Value #
const arr = [1, 2, 3, 2, 1];
console.log(arr.lastIndexOf(2)); // 3
console.log(arr.lastIndexOf(1)); // 4
includes() - Check if Value Exists #
const arr = [1, 2, 3, 4, 5];
console.log(arr.includes(3)); // true
console.log(arr.includes(99)); // false
console.log(arr.includes(2, 2)); // false (start from index 2)
Testing Arrays #
some() - At Least One Passes Test #
const numbers = [1, 2, 3, 4, 5];
const hasEven = numbers.some(n => n % 2 === 0);
console.log(hasEven); // true
const hasNegative = numbers.some(n => n < 0);
console.log(hasNegative); // false
every() - All Pass Test #
const numbers = [2, 4, 6, 8];
const allEven = numbers.every(n => n % 2 === 0);
console.log(allEven); // true
const allPositive = numbers.every(n => n > 0);
console.log(allPositive); // true
Sorting and Reversing #
sort() - Sort Array #
// Numbers (WRONG - sorts as strings)
const numbers = [10, 5, 40, 25, 1000, 1];
numbers.sort();
console.log(numbers); // [1, 10, 1000, 25, 40, 5] - Wrong!
// Numbers (CORRECT)
numbers.sort((a, b) => a - b); // Ascending
console.log(numbers); // [1, 5, 10, 25, 40, 1000]
numbers.sort((a, b) => b - a); // Descending
console.log(numbers); // [1000, 40, 25, 10, 5, 1]
// Strings
const words = ['banana', 'apple', 'cherry'];
words.sort();
console.log(words); // ['apple', 'banana', 'cherry']
// Objects
const users = [
{ name: 'Charlie', age: 25 },
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 20 }
];
users.sort((a, b) => a.age - b.age);
console.log(users); // Sorted by age ascending
users.sort((a, b) => a.name.localeCompare(b.name));
console.log(users); // Sorted by name alphabetically
reverse() - Reverse Array #
const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // [5, 4, 3, 2, 1]
toSorted() and toReversed() - Non-Mutating #
const arr = [3, 1, 2];
const sorted = arr.toSorted((a, b) => a - b);
console.log(sorted); // [1, 2, 3]
console.log(arr); // [3, 1, 2] - unchanged
const reversed = arr.toReversed();
console.log(reversed); // [2, 1, 3]
console.log(arr); // [3, 1, 2] - unchanged
Combining Arrays #
concat() - Merge Arrays #
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
const combined = arr1.concat(arr2, arr3);
console.log(combined); // [1, 2, 3, 4, 5, 6]
// With spread operator (modern)
const combined2 = [...arr1, ...arr2, ...arr3];
console.log(combined2); // [1, 2, 3, 4, 5, 6]
flat() - Flatten Nested Arrays #
const nested = [1, [2, 3], [4, [5, 6]]];
const flat1 = nested.flat();
console.log(flat1); // [1, 2, 3, 4, [5, 6]]
const flat2 = nested.flat(2);
console.log(flat2); // [1, 2, 3, 4, 5, 6]
const flatAll = nested.flat(Infinity);
console.log(flatAll); // [1, 2, 3, 4, 5, 6]
flatMap() - Map Then Flatten #
const arr = [1, 2, 3];
const doubled = arr.flatMap(n => [n, n * 2]);
console.log(doubled); // [1, 2, 2, 4, 3, 6]
const words = ['hello world', 'foo bar'];
const allWords = words.flatMap(phrase => phrase.split(' '));
console.log(allWords); // ['hello', 'world', 'foo', 'bar']
Extracting Portions #
slice() - Extract Portion (Non-Mutating) #
const arr = [1, 2, 3, 4, 5];
const portion = arr.slice(1, 4);
console.log(portion); // [2, 3, 4]
console.log(arr); // [1, 2, 3, 4, 5] - unchanged
const lastTwo = arr.slice(-2);
console.log(lastTwo); // [4, 5]
const copy = arr.slice();
console.log(copy); // [1, 2, 3, 4, 5]
splice() - Add/Remove Elements (Mutating) #
const arr = [1, 2, 3, 4, 5];
// Remove elements
const removed = arr.splice(2, 2);
console.log(removed); // [3, 4]
console.log(arr); // [1, 2, 5]
// Insert elements
arr.splice(2, 0, 10, 11);
console.log(arr); // [1, 2, 10, 11, 5]
// Replace elements
arr.splice(1, 2, 99);
console.log(arr); // [1, 99, 11, 5]
toSpliced() - Non-Mutating Version #
const arr = [1, 2, 3, 4, 5];
const newArr = arr.toSpliced(2, 2, 99);
console.log(newArr); // [1, 2, 99, 5]
console.log(arr); // [1, 2, 3, 4, 5] - unchanged
Converting Arrays #
join() - Array to String #
const arr = ['a', 'b', 'c'];
console.log(arr.join()); // 'a,b,c'
console.log(arr.join('')); // 'abc'
console.log(arr.join(' - ')); // 'a - b - c'
toString() - Array to String #
const arr = [1, 2, 3];
console.log(arr.toString()); // '1,2,3'
Array.from() - Convert to Array #
// String to array
const str = 'hello';
const arr1 = Array.from(str);
console.log(arr1); // ['h', 'e', 'l', 'l', 'o']
// Set to array
const set = new Set([1, 2, 3]);
const arr2 = Array.from(set);
console.log(arr2); // [1, 2, 3]
// With mapping function
const arr3 = Array.from([1, 2, 3], n => n * 2);
console.log(arr3); // [2, 4, 6]
Other Useful Methods #
fill() - Fill with Value #
const arr = [1, 2, 3, 4, 5];
arr.fill(0);
console.log(arr); // [0, 0, 0, 0, 0]
const arr2 = [1, 2, 3, 4, 5];
arr2.fill(99, 2, 4);
console.log(arr2); // [1, 2, 99, 99, 5]
copyWithin() - Copy Part of Array #
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3);
console.log(arr); // [4, 5, 3, 4, 5]
at() - Get Element at Index #
const arr = [1, 2, 3, 4, 5];
console.log(arr.at(0)); // 1
console.log(arr.at(-1)); // 5 (last element)
console.log(arr.at(-2)); // 4
with() - Non-Mutating Update #
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 99);
console.log(newArr); // [1, 2, 99, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5] - unchanged
Chaining Methods #
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = numbers
.filter(n => n % 2 === 0) // [2, 4, 6, 8, 10]
.map(n => n * 2) // [4, 8, 12, 16, 20]
.reduce((sum, n) => sum + n, 0); // 60
console.log(result); // 60
Performance Considerations #
| Method | Mutates | Returns | Time Complexity |
|---|---|---|---|
| push/pop | Yes | Single value | O(1) |
| shift/unshift | Yes | Single value | O(n) |
| splice | Yes | Array | O(n) |
| slice | No | Array | O(n) |
| concat | No | Array | O(n) |
| map/filter | No | Array | O(n) |
| find/findIndex | No | Single value | O(n) |
| sort | Yes | Array | O(n log n) |
Best Practices #
- Use const for arrays you won’t reassign
- Prefer immutable methods for predictability
- Chain methods for readable transformations
- Use appropriate methods - don’t use forEach when you need map
- Avoid mutations in production code
- Use spread operator instead of concat
- Use for…of for early exit needs
Array methods make JavaScript data manipulation elegant and efficient. Master these and you’ll write cleaner, more expressive code.