Chapters: JavaScript HTML & CSS JSON XML YAML Go Java ← Full TOC

← JavaScript Index

📋 Arrays & Iteration — Array methods — map, filter, reduce, find, flat, sort

JavaScript arrays have a rich set of functional methods. All return new arrays (immutable style) except sort() and reverse() which mutate in place. Use slice() to copy first.

📋 Methods & APIs

NameSignature / SyntaxDescription
push / poparr.push(x) / arr.pop()Add/remove from end
shift / unshiftarr.shift() / arr.unshift(x)Remove/add at start
splicearr.splice(start, deleteCount, ...items)Remove/insert at position (mutates)
slicearr.slice(start, end) → newArrReturn shallow copy of portion
concatarr.concat(arr2) → newArrReturn new array with arr2 appended
maparr.map(fn) → newArrTransform each element
filterarr.filter(fn) → newArrKeep elements where fn returns true
reducearr.reduce((acc,val) => acc+val, init)Fold to single value
reduceRightarr.reduceRight(fn, init)Reduce from right to left
findarr.find(fn) → elementFirst element where fn is true
findIndexarr.findIndex(fn) → indexIndex of first match
findLastarr.findLast(fn) → elementLast element where fn is true (ES2023)
somearr.some(fn) → boolTrue if any element matches
everyarr.every(fn) → boolTrue if all elements match
includesarr.includes(val) → boolTrue if array contains val
indexOfarr.indexOf(val) → indexFirst index of val (-1 if absent)
flatarr.flat(depth) → newArrFlatten nested arrays
flatMaparr.flatMap(fn) → newArrMap then flatten one level
sortarr.sort((a,b) => a-b)Sort in place — always pass comparator for numbers!
reversearr.reverse()Reverse in place
forEacharr.forEach(fn)Execute fn for each element (no return value)
joinarr.join(sep) → stringJoin elements into string
fillarr.fill(val, start, end)Fill with value in range
Array.fromArray.from(iterable, mapFn)Create array from iterable or array-like
Array.ofArray.of(1,2,3) → [1,2,3]Create array from arguments
Array.isArrayArray.isArray(val) → boolTrue if val is an Array
entries/keys/valuesarr.entries() / .keys() / .values()Iterator over [index,value] / indices / values
atarr.at(-1)Access by index, supports negative (ES2022)
toSorted/toReversedarr.toSorted() / arr.toReversed()Non-mutating sort/reverse (ES2023)
structuredClonestructuredClone(obj)Deep clone any serializable object

💡 Example

Run with node script.js or save as HTML and open in browser.

// Array methods — functional style
const students = [
  { name: 'Alice',  score: 95, subject: 'Math'    },
  { name: 'Bob',    score: 87, subject: 'Science'  },
  { name: 'Carol',  score: 92, subject: 'Math'     },
  { name: 'Dave',   score: 78, subject: 'Science'  },
  { name: 'Eve',    score: 98, subject: 'Math'     },
];

// filter + map + sort
const topMath = students
  .filter(s => s.subject === 'Math' && s.score >= 90)
  .map(s => `\${s.name}(\${s.score})`)
  .sort();
console.log('Top Math:', topMath);

// reduce: group by subject
const bySubject = students.reduce((acc, s) => {
  (acc[s.subject] = acc[s.subject] || []).push(s);
  return acc;
}, {});
for (const [subj, group] of Object.entries(bySubject)) {
  const avg = group.reduce((sum, s) => sum + s.score, 0) / group.length;
  console.log(`\${subj}: avg=\${avg.toFixed(1)} n=\${group.length}`);
}

// find / findIndex
const best = students.reduce((a, b) => a.score > b.score ? a : b);
console.log('Best:', best.name, best.score);

// flat / flatMap
const matrix = [[1,2,3],[4,5,6],[7,8,9]];
console.log(matrix.flat());
const pairs = [1,2,3].flatMap(n => [n, n*n]);
console.log(pairs);  // [1,1,2,4,3,9]

// Array.from with map
const squares = Array.from({length:10}, (_, i) => (i+1)**2);
console.log(squares);

// Immutable sort (ES2023)
const sorted = students.toSorted((a,b) => b.score - a.score);
console.log('Sorted (immutable):', sorted.map(s=>s.name));
// node script.js

← ES6+ Core  |  🏠 Index  |  Promises & Async →