Topic 05 / 15

Arrays — map, filter, reduce & Friends

~11 min read  //  JavaScript Series  //  Coding India

Array Basics

const stack = ["js", "css", "react"];

stack.length            // 3
stack[0]                // 'js'
stack.at(-1)            // 'react' — negative indexing
stack.push("node");     // add to end
stack.pop();            // remove from end
stack.includes("css")   // true
stack.indexOf("react")  // 2
stack.slice(0, 2)       // ['js','css'] — copy, original untouched
stack.join(" → ")       // 'js → css → react'

The Big Three

map — transform every element into a new array (same length):

const prices = [100, 250, 400];
const withTax = prices.map(p => p * 1.18);
// [118, 295, 472]

filter — keep elements that pass a test:

const scores = [82, 41, 99, 67];
const passed = scores.filter(s => s >= 60);
// [82, 99, 67]

reduce — boil an array down to one value:

const total = prices.reduce((acc, p) => acc + p, 0);
// 750 — acc starts at 0, accumulates each p

They chain beautifully:

const revenue = orders
  .filter(o => o.status === "paid")
  .map(o => o.amount)
  .reduce((sum, n) => sum + n, 0);

Searching & Testing

users.find(u => u.id === 42)        // first match (or undefined)
users.findIndex(u => u.id === 42)   // its index (or -1)
scores.some(s => s > 90)            // true if ANY pass
scores.every(s => s >= 0)           // true if ALL pass

Sorting — Two Traps

[10, 9, 100].sort()                  // [10, 100, 9] — sorts as STRINGS!
[10, 9, 100].sort((a, b) => a - b)   // [9, 10, 100] — always pass a comparator

// sort() mutates! Use toSorted() for a copy (ES2023)
const ranked = players.toSorted((a, b) => b.score - a.score);

Destructuring & Spread

const [first, second, ...rest] = ["js", "css", "react", "node"];
// first='js', second='css', rest=['react','node']

const copy = [...stack];                 // shallow copy
const merged = [...listA, ...listB];     // concat
const unique = [...new Set([1, 2, 2, 3])];   // dedupe → [1,2,3]

flat & flatMap

[[1, 2], [3, 4]].flat()                 // [1, 2, 3, 4]
posts.flatMap(p => p.tags)              // map then flatten one level

Choosing: need a transformed array → map; a subset → filter; one value → reduce; a side effect per item → forEach or for...of.