Choosing the right array method
| Method | Result | Mutates array? |
|---|---|---|
| map(), filter(), flatMap() | New array | No |
| reduce() | Any value | No |
| find() | Element or undefined | No |
| some(), every(), includes() | Boolean | No |
| sort(), reverse() | Same array | Yes |
| toSorted(), toReversed(), toSpliced(), with() | New array | No |
const prices = [100, 250, 80];
const doubledPrices = prices.map((price) => price * 2);
const selectedPrices = prices.filter((price) => price >= 100);
const totalPrice = prices.reduce((sum, price) => sum + price, 0);
console.log(doubledPrices); // [200, 500, 160]
console.log(selectedPrices); // [100, 250]
console.log(totalPrice); // 430
map, filter and reduce answer distinct questions: how to transform entries, which entries to retain and how to combine them. A typical map or filter callback receives value, index and array; reduce receives the accumulator first. Map preserves length, filter produces an array of selected elements and reduce can produce any value. forEach returns undefined and is appropriate for side effects rather than constructing a result. [1][2][3][4][5][12]
map and filter: transforming API data
const products = [
{ id: 1, price: 100, active: true },
{ id: 2, price: 50, active: false },
];
const activeProducts = products
.filter((product) => product.active)
.map(({ id, price }) => ({ id, price }));
const numericValues = ["10", "20", "30"].map((value) =>
Number.parseInt(value, 10),
);
const values = [0, false, "", null, undefined];
const presentValues = values.filter(
(value) => value !== null && value !== undefined,
);
console.log(activeProducts); // [{ id: 1, price: 100 }]
console.log(numericValues); // [10, 20, 30]
console.log(presentValues); // [0, false, ""]
Discard unwanted records before transforming the rest, especially if the transformation is expensive. A block-bodied arrow callback in map needs a return statement; otherwise the mapped values are undefined. [3][4]
Passing parseInt directly to map is unsafe because the index becomes its radix argument. filter(Boolean) also removes valid zero, false and empty-string values. To remove only null and undefined, use v != null or explicitly compare against both. [3][4]
reduce: totals, aggregation and accumulators
const cartItems = [
{ id: 1, priceCents: 1999, quantity: 2 },
{ id: 2, priceCents: 500, quantity: 3 },
];
function calculateTotalCents(items) {
return items.reduce(
(total, item) => total + item.priceCents * item.quantity,
0,
);
}
const totalCents = calculateTotalCents(cartItems);
const emptyTotal = calculateTotalCents([]);
const itemsById = new Map(cartItems.map((item) => [item.id, item]));
console.log(totalCents); // 5498
console.log(emptyTotal); // 0
console.log(itemsById.get(2)?.quantity); // 3
Choose an initial value matching the desired output: zero for a sum, a new object or Map for grouping. Without one, an empty array throws TypeError and a one-element array may not call the callback. [5]
The example stores prices in minor currency units to avoid some floating-point fraction problems; values must stay within the safe integer range. A Map is often clearer for indexing by ID than repeated searches. Spreading a growing accumulator on every iteration can introduce quadratic work. [5]
find, findIndex, some, every and includes
const tasks = [
{ id: 1, done: false },
{ id: 2, done: true },
];
const completedTask = tasks.find((task) => task.id === 2);
const missingIndex = tasks.findIndex((task) => task.id === 3);
const hasCompletedTask = tasks.some((task) => task.done);
const allTasksCompleted = tasks.every((task) => task.done);
console.log(completedTask); // { id: 2, done: true }
console.log(missingIndex); // -1
console.log(hasCompletedTask); // true
console.log(allTasksCompleted); // false
console.log([NaN].includes(NaN)); // true
console.log([NaN].indexOf(NaN)); // -1
console.log([].some(Boolean)); // false
console.log([].every(Boolean)); // true
find returns the first match or undefined; findIndex returns its index or -1. Some and every short-circuit, returning false and true respectively for an empty array. [2][6][7]
Includes checks membership, recognizes NaN and compares objects by identity rather than contents. Avoid filter(...)[0] if only the first match matters: filter visits all existing entries. If undefined is itself a valid element, a find result alone cannot distinguish absence from a match. [2][6][7]
sort and toSorted: numbers, strings and stability
const numbers = [10, 2, 100];
const sortedNumbers = numbers.toSorted((first, second) => first - second);
const collator = new Intl.Collator("en", { numeric: true });
const fileNames = ["file10", "file2"];
const sortedFileNames = fileNames.toSorted(collator.compare);
const sortedFallback = [...numbers].sort((first, second) => first - second);
console.log(sortedNumbers); // [2, 10, 100]
console.log(numbers); // [10, 2, 100]
console.log(sortedFileNames); // ["file2", "file10"]
console.log(sortedFallback); // [2, 10, 100]
Default sorting converts values to strings, so 100 can precede 2. For valid numbers use (a, b) => a - b; comparators should be consistent, side-effect-free and return negative, zero or positive numbers. Sorting is stable: equal entries retain relative order. [9][10][17]
Sort mutates the input; toSorted creates a new array. For user-facing strings use Intl.Collator with the user's locale; numeric comparison naturally orders file2 before file10. Older runtimes can copy before sorting; check support for newer methods. [9][10][17]
Mutation: slice, splice, with and state updates
const tasks = [
{ id: 1, done: false },
{ id: 2, done: false },
];
function completeTask(tasks, taskId) {
return tasks.map((task) => {
if (task.id !== taskId) {
return task;
}
return { ...task, done: true };
});
}
const updatedTasks = completeTask(tasks, 1);
console.log(tasks[0].done); // false
console.log(updatedTasks[0].done); // true
console.log(tasks[1] === updatedTasks[1]); // true
const ids = [1, 2, 3];
console.log(ids.slice(0, 2)); // [1, 2]
console.log(ids.toSpliced(1, 1)); // [1, 3]
console.log(ids.with(0, 9)); // [9, 2, 3]
Push, pop, shift, unshift, splice, sort and reverse modify the input. Slice copies a range excluding the end index; splice modifies the source and returns removed entries. ToSpliced, toReversed, toSorted and with create new arrays. [2][10][11][16][18][19]
These are shallow copies, so nested objects remain shared. When updating React state, also copy the changed object and changed nested paths while retaining unchanged references. Cloning the entire data tree is unnecessary. [2][10][11][16][18][19]
flatMap, grouping and deduplication
const orders = [
{ status: "paid", itemIds: [1, 2] },
{ status: "draft", itemIds: [3] },
];
const paidItemIds = orders.flatMap((order) => {
if (order.status !== "paid") {
return [];
}
return order.itemIds;
});
const ordersByStatus = Object.groupBy(orders, (order) => order.status);
const uniqueIds = [...new Set([1, 2, 1, 3])];
console.log(paidItemIds); // [1, 2]
console.log(ordersByStatus.paid?.length); // 1
console.log(uniqueIds); // [1, 2, 3]
FlatMap transforms and flattens the result by one level. Its callback can return zero, one or multiple entries, useful for extracting line items from paid orders. Object.groupBy returns a null-prototype object keyed by strings or symbols; Map.groupBy also supports object keys. [2][8][14][15]
Both preserve item references. Set removes duplicate primitive values, but separately allocated objects with identical IDs are distinct. Use a Map keyed by ID when deduplicating records and define which record wins. [2][8][14][15]
Sparse arrays and changes during iteration
const sparseNumbers = [1, , 3];
const doubledNumbers = sparseNumbers.map((number) => number * 2);
const denseNumbers = sparseNumbers.filter(() => true);
const firstMissingIndex = sparseNumbers.findIndex(
(number) => number === undefined,
);
console.log(doubledNumbers.length); // 3
console.log(1 in doubledNumbers); // false
console.log(denseNumbers); // [1, 3]
console.log(firstMissingIndex); // 1
console.log(Array.from(sparseNumbers)); // [1, undefined, 3]
[1, , 3] differs from [1, undefined, 3]. Map preserves holes, filter skips them and returns a dense array, and find and findIndex read holes like undefined. [1][2][3][4][6]
In ordinary arrays without unusual prototype properties, Array.from makes missing positions explicit undefined values. Most iterative methods capture the starting length but read values as they proceed. Adding, deleting or shifting entries inside callbacks can therefore produce skipped or surprising results. [1][2][3][4][6]
Asynchronous operations: map versus forEach
async function loadProduct(productId) {
// Simulated asynchronous data source.
await Promise.resolve();
return { id: productId, ready: true };
}
async function loadProductsSequentially(productIds) {
const products = [];
for (const productId of productIds) {
const product = await loadProduct(productId);
products.push(product);
}
return products;
}
async function main() {
const productIds = [1, 2, 3];
const concurrentProducts = await Promise.all(productIds.map(loadProduct));
const sequentialProducts = await loadProductsSequentially(productIds);
console.log(concurrentProducts);
console.log(sequentialProducts);
}
main().catch((error) => {
console.error(error);
});
ForEach with an async callback does not await the returned promises, so await array.forEach(...) does not wait for the work. Async map produces an array of promises; Promise.all returns results in input order. [12][13]
One rejection rejects the aggregate but does not cancel remaining operations. Use for...of with await for dependent operations and bounded concurrency for large batches. An async filter callback does not work as an asynchronous predicate either, because a Promise is truthy. [12][13]
Method chains, performance and a practical data view
const products = [
{ id: 1, active: true, priceCents: 200 },
{ id: 2, active: false, priceCents: 300 },
{ id: 3, active: true, priceCents: 100 },
];
const visibleProducts = products
.filter((product) => product.active)
.toSorted((first, second) => first.priceCents - second.priceCents)
.map(({ id, priceCents }) => ({ id, priceCents }));
const activeTotalCents = products.reduce((total, product) => {
if (!product.active) {
return total;
}
return total + product.priceCents;
}, 0);
console.log(visibleProducts);
// [{ id: 3, priceCents: 100 }, { id: 1, priceCents: 200 }]
console.log(activeTotalCents); // 300
Filter and map make separate passes and usually allocate intermediate arrays, but readability often outweighs allocations for ordinary UI lists. If only a total is needed, a single reduce suffices without constructing a filtered list. [5][9]
When filtering and sorting thousands of records, reduce the input before sorting, avoid repeating expensive calculations in comparators and measure realistic data. The standard does not prescribe one universal sorting complexity. A single loop may reduce allocations on a hot path, but is not guaranteed to be faster. [5][9]
