JavaScript Array Methods
A quick reference for adding, transforming, searching, and ordering items in JavaScript arrays.
TL;DR
- 01Use
push(),pop(),shift(), andunshift()to add or remove items. - 02Use
map(),filter(), andreduce()to transform array data. - 03Use
find(),some(), andincludes()to search arrays.
Tips
- 01Prefer non-mutating methods like
map,filter, andslicewhen you want to keep your original array unchanged. - 02Chain
map,filter, andreducetogether to transform data in one readable pipeline instead of writing several separate loops.
Warnings
- 01Sort and reverse change the original array in place, so copy first if you need to keep the source order.
- 02
splice()also mutates the original array, and the wrong delete count can silently remove items you meant to keep.
Add and Remove
push()Adds one or more items to the end, returns the new length.
const cart = ['apple'];
cart.push('banana'); // 2pop()Removes and returns the last item.
const stack = ['init', 'save', 'close'];
stack.pop(); // 'close'shift()Removes and returns the first item.
const queue = ['first', 'second', 'third'];
queue.shift(); // 'first'unshift()Adds one or more items to the front, returns the new length.
const updates = ['old'];
updates.unshift('new'); // 2splice()Inserts, removes, or replaces items at any index. Mutates in place.
const list = ['a', 'b', 'c'];
list.splice(1, 1, 'x'); // returns ['b']
// list is now ['a', 'x', 'c']Copy and Combine
concat()Merges two or more arrays into a new array without mutation.
const arr1 = [1, 2];
arr1.concat([3, 4]); // [1, 2, 3, 4]spread operatorCopies or combines arrays cleanly without mutation.
const a = [1, 2];
const b = [...a, 3]; // [1, 2, 3]
const merged = [...a, ...b, ...c]; // all combinedslice()Copies a whole array or a portion without mutating the source.
const arr = [1, 2, 3, 4];
arr.slice(1, 3); // [2, 3]Array.of()Builds a new array from arguments, even a single number.
Array.of(7); // [7]
Array(7); // empty array with length 7Transform Data
map()Creates a new array by transforming every element with a function.
const prices = [10, 20, 30];
prices.map(p => p * 1.1); // [11, 22, 33]filter()Returns a new array keeping only items that pass the test.
const users = [{active: true}, {active: false}];
users.filter(u => u.active); // [{active: true}]reduce()Combines all items into a single value; always pass an initial value.
const nums = [1, 2, 3];
nums.reduce((acc, n) => acc + n, 0); // 6Search and Test
find()Returns the first element matching a condition, or undefined.
users.find(u => u.id === 1); // {id: 1, ...}findIndex()Returns the index of the first match, or -1 if not found.
users.findIndex(u => u.id === 1); // 0includes()Returns true if the exact value exists in the array.
['read', 'write'].includes('write'); // truesome()Returns true if at least one element passes the test.
users.some(u => u.isAdmin); // true or falseevery()Returns true only if all elements pass the test.
tasks.every(t => t.done); // true or falseOrder and Display
sort()Sorts the array in place; always pass a comparator for reliable results.
names.sort((a, b) => a.localeCompare(b));reverse()Flips the order of items in place.
[1, 2, 3].reverse(); // [3, 2, 1]join()Combines all elements into a string with a separator.
['a', 'b', 'c'].join(','); // "a,b,c"forEach()Runs a function on each item for side effects; returns undefined.
items.forEach(item => console.log(item));Array.from()Converts any iterable — string, Set, NodeList — into a real array.
Array.from('hi'); // ['h', 'i']
Array.from(new Set([1,1,2])); // [1, 2]Flatten and Access
flat()Collapses nested arrays one level deep; pass a depth to go deeper.
const nested = [1, [2, [3]]];
nested.flat(); // [1, 2, [3]]
nested.flat(2); // [1, 2, 3]flatMap()Maps over items and flattens the result one level in a single pass.
const words = ['hi there', 'foo bar'];
words.flatMap(s => s.split(' '));
// ['hi', 'there', 'foo', 'bar']at()Accesses an element by index; negative values count from the end.
const arr = [10, 20, 30, 40];
arr.at(0); // 10
arr.at(-1); // 40fill()Overwrites a range of elements with a static value in place.
const arr = [1, 2, 3, 4, 5];
arr.fill(0, 1, 3); // [1, 0, 0, 4, 5]Array.isArray()Safely checks whether a value is an array at runtime.
Array.isArray([1, 2]); // true
Array.isArray('abc'); // falseIn Practice
Chains filter, map, sort, and reduce on an order list to compute tax-adjusted revenue in one readable pipeline.
- 01
filter()removes pending and cancelled orders before they reach the revenue calculation. - 02
map()adds a tax-adjustedtotalfield to each order without mutating the originals. - 03
sort()reorders results from highest to lowest total. - 04
reduce()sums every total into a single revenue figure, starting from zero. - 05
at(0)retrieves the top order; negative indexes likeat(-1)work too.
const orders = [
{ name: 'Keyboard', price: 89.99, status: 'completed' },
{ name: 'Monitor', price: 349.99, status: 'pending' },
{ name: 'Mouse', price: 49.99, status: 'completed' },
{ name: 'Webcam', price: 79.99, status: 'completed' },
{ name: 'Headset', price: 129.99, status: 'cancelled' },
];
const summary = orders
.filter(o => o.status === 'completed')
.map(o => ({ ...o, total: +(o.price * 1.08).toFixed(2) }))
.sort((a, b) => b.total - a.total);
const revenue = summary.reduce((acc, o) => acc + o.total, 0);
console.log('Top order:', summary.at(0).name); // 'Keyboard'
console.log(`Revenue (after tax): $${revenue.toFixed(2)}`); // $237.57FAQ
Use [...new Set(array)] to deduplicate primitives in one line. For objects, filter by a unique key instead: array.filter((item, i, arr) => arr.findIndex(x => x.id === item.id) === i).
map() returns a new array of transformed values and is chainable. forEach() always returns undefined and exists purely for side effects. If you need the result, use map().
Use findIndex() with a callback — it returns the index of the first match or -1 if none found. Use indexOf() only when searching for an exact primitive value, since it can't accept a predicate.
Use the spread operator: const merged = [...arr1, ...arr2], or arr1.concat(arr2). Both return a new array and leave the originals unchanged.
Without an initial value, reduce() uses the first element as the accumulator and starts iterating at index 1. This silently breaks with empty arrays, which throw, or when the first element is the wrong type. Always pass an explicit initial value as the second argument.
[1, 2, 3].reduce((sum, n) => sum + n, 0); // 6
[].reduce((sum, n) => sum + n, 0); // 0
[].reduce((sum, n) => sum + n); // TypeError