CPCODELAB
JavaScript

map, filter, reduce, find, sort, and More

13 min read

Higher-Order Array Methods

These methods take a callback function and let you transform, filter, and aggregate arrays in a declarative style — expressing *what* you want rather than *how* to loop.

map — Transform Every Element

javascript
const prices = [10, 20, 30];
const withTax = prices.map(p => p * 1.1);
// [11, 22, 33]

filter — Keep Matching Elements

javascript
const scores = [45, 80, 92, 35, 76];
const passing = scores.filter(s => s >= 60);
// [80, 92, 76]

reduce — Accumulate to a Single Value

javascript
const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((acc, n) => acc + n, 0); // 15

// Group by category
const items = [
  { name: "apple", type: "fruit" },
  { name: "banana", type: "fruit" },
  { name: "carrot", type: "veg" }
];
const grouped = items.reduce((acc, item) => {
  (acc[item.type] ||= []).push(item.name);
  return acc;
}, {});
// { fruit: ["apple","banana"], veg: ["carrot"] }

find, findIndex, some, every

javascript
const users = [
  { id: 1, name: "Alice", active: true },
  { id: 2, name: "Bob",   active: false },
  { id: 3, name: "Carol", active: true }
];

users.find(u => u.id === 2);       // { id:2, name:"Bob", ... }
users.findIndex(u => u.id === 2);  // 1
users.some(u => !u.active);        // true
users.every(u => u.active);        // false

sort

sort mutates the array and, by default, coerces elements to strings for comparison. Always provide a compare function for numbers.

javascript
[10, 9, 100].sort();              // [10, 100, 9] WRONG!
[10, 9, 100].sort((a, b) => a-b); // [9, 10, 100] correct

// Sort objects by name alphabetically
users.sort((a, b) => a.name.localeCompare(b.name));

You can chain these methods: arr.filter(x => x > 0).map(x => x * 2).reduce((a,b) => a + b, 0). Each method returns a new array (except reduce) so the original is never modified.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises