Array Methods You Must Know
Source: Dev.to
Mutating Methods (Change Original Array)
push()– Add to endpop()– Remove from endshift()– Remove from startunshift()– Add to start
All of these do not return a new array; they modify the original array.
Non‑Mutating Methods (Do NOT Change Original)
map()– Transform data → returns a new arrayfilter()– Select data → returns a new arrayforEach()– Loop only → returns nothingreduce()– Combine values → returns a single value
push() and pop()
push()
Adds an element to the end of the array.
let fruits = ["apple", "banana"];
fruits.push("orange");
// fruits is now ["apple", "banana", "orange"]
pop()
Removes the last element from the array.
let fruits = ["apple", "banana", "orange"];
fruits.pop();
// fruits is now ["apple", "banana"]
shift() and unshift()
unshift()
Adds an element to the beginning of the array.
let numbers = [2, 3, 4];
numbers.unshift(1);
// numbers is now [1, 2, 3, 4]
shift()
Removes the first element from the array.
let numbers = [1, 2, 3, 4];
numbers.shift();
// numbers is now [2, 3, 4]
map()
Creates a new array by applying a function to each element of the original array.
let numbers = [1, 2, 3];
let doubled = numbers.map(e => e * 2);
console.log(doubled); // [1, 2, 6] (as shown in the original example)
console.log(numbers); // [1, 2, 3]
How map works
[1, 2, 3]
↓ ↓ ↓
×2 ×2 ×2
↓ ↓ ↓
[2, 4, 6]
filter()
Selects elements that satisfy a given condition and returns a new array.
let numbers = [1, 2, 3, 4];
// Example: keep only even numbers
let evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
reduce()
Combines array elements into a single value using a reducer function.
let numbers = [1, 2, 3, 4];
// Example: sum all numbers
let sum = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // 10
forEach()
Executes a provided function once for each array element. It does not return a new array.
let fruits = ["apple", "banana", "orange"];
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// Output:
// 0: apple
// 1: banana
// 2: orange