← Learning Hub
Intermediate

Array Methods: map, filter, reduce

Arrays have powerful methods that replace most for loops. They take a small function and run it for every item.

These methods describe what you want instead of how to loop: filter = "keep the ones that...", map = "turn each one into...", reduce = "combine them all into one value", find = "give me the first one that...". Code written this way is shorter and easier to read, and it's the standard style in React, Angular and Node.js.

map and filter always return a new array and leave the original alone, which avoids accidental changes to data other parts of your app are using.

Example
const prices = [499, 1299, 199, 2499];

// map: change every item -> a new array of the same length
const withGst = prices.map(p => Math.round(p * 1.18));
console.log(withGst);      // Output: [ 589, 1533, 235, 2949 ]

// filter: keep only items that pass a test
const cheap = prices.filter(p => p < 1000);
console.log(cheap);        // Output: [ 499, 199 ]

// reduce: boil the array down to one value
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total);        // Output: 4496

Finding things

Example
const products = [
  { name: "Pen", price: 20 },
  { name: "Bag", price: 900 },
  { name: "Book", price: 150 },
];

console.log(products.find(p => p.price > 100).name);   // Output: Bag
console.log(products.findIndex(p => p.name === "Book")); // Output: 2
console.log(products.some(p => p.price > 500));          // Output: true
console.log(products.every(p => p.price > 50));          // Output: false
console.log(products.map(p => p.name).join(", "));       // Output: Pen, Bag, Book

Sorting

sort() changes the array itself. For numbers, always give a compare function - without it, numbers are sorted like words ("100" comes before "20").

Example
const nums = [100, 20, 3];
console.log([...nums].sort());                 // Output: [ 100, 20, 3 ]
console.log([...nums].sort((a, b) => a - b));  // Output: [ 3, 20, 100 ]

const byPrice = [...products].sort((a, b) => b.price - a.price);
console.log(byPrice[0].name);                  // Output: Bag
Example
<!DOCTYPE html>
<html>
  <body>
    <pre id="out"></pre>
    <script>
      function show(...values) {
        document.getElementById("out").textContent += values.join(" ") + "\n";
      }
      const cart = [
        { name: "Shirt", price: 799, qty: 2 },
        { name: "Shoes", price: 2499, qty: 1 },
        { name: "Socks", price: 199, qty: 3 },
      ];
      const lines = cart.map(i => `${i.name}: ₹${i.price * i.qty}`);
      show(lines.join("\n"));
      const total = cart.reduce((s, i) => s + i.price * i.qty, 0);
      show("Total: ₹" + total);
      show("Items over ₹500:", cart.filter(i => i.price > 500).map(i => i.name).join(", "));
    </script>
  </body>
</html>
▶ Try it yourself
You can chain methods: cart.filter(...).map(...).reduce(...). Read the chain from left to right like a recipe.
Key points
  • map transforms, filter keeps, reduce combines, find returns one item.
  • some / every answer yes-or-no questions.
  • Give sort() a compare function for numbers.
  • Chain methods like a recipe.

📝 Test yourself

1. Which method makes a new array with every item changed?
2. What does [5, 10, 15].reduce((s, n) => s + n, 0) give?
3. Why write sort((a, b) => a - b) for numbers?