mosaddik.dev
All posts

JavaScript map, filter and reduce explained, with real examples

Mosaddik Billah 4 min read

JavaScript & React

Lines of colourful JavaScript code on a dark screen
Photo by Markus Spiske on Unsplash
On this page
  1. map: change every item
  2. filter: keep some items
  3. reduce: turn many items into one value
  4. Chaining them together
  5. Which one should I use?
  6. Common mistakes
  7. Where you’ll use this

map, filter and reduce are three array methods you’ll use in almost every JavaScript project, from React components to Wix Velo code. Each one replaces a common kind of for loop with a shorter, clearer line. This guide uses one small set of product data so you can see what each method does to it.

JavaScript
const products = [
  { name: "Notebook", price: 250, category: "stationery", inStock: true },
  { name: "Pen set", price: 180, category: "stationery", inStock: false },
  { name: "Desk lamp", price: 1400, category: "home", inStock: true },
  { name: "Mug", price: 350, category: "home", inStock: true },
];

map: change every item#

map runs a function on each item and returns a new array of the same length with the results.

JavaScript
const names = products.map((product) => product.name);
// ["Notebook", "Pen set", "Desk lamp", "Mug"]

const withTax = products.map((product) => ({
  ...product,
  priceWithTax: Math.round(product.price * 1.15),
}));

Use map when you want one output for every input: names for a dropdown, prices formatted for display, or data reshaped for an API.

The original array isn’t changed. In the second example, { ...product } copies each product before adding a field, so products stays as it was.

filter: keep some items#

filter returns a new array with only the items for which your function returns true.

JavaScript
const available = products.filter((product) => product.inStock);
// Notebook, Desk lamp, Mug

const cheapStationery = products.filter(
  (product) => product.category === "stationery" && product.price < 200
);
// Pen set

If nothing matches, you get an empty array, not undefined, so code that loops over the result keeps working.

reduce: turn many items into one value#

reduce walks through the array and carries a running value, often called the accumulator, from one item to the next. You give it a function and a starting value.

JavaScript
const total = products.reduce((sum, product) => sum + product.price, 0);
// 2180

On each step, sum is the result so far and product is the current item. The 0 at the end is where sum starts.

reduce can build any shape, not only numbers. Here it groups products by category:

JavaScript
const byCategory = products.reduce((groups, product) => {
  (groups[product.category] ??= []).push(product.name);
  return groups;
}, {});
// { stationery: ["Notebook", "Pen set"], home: ["Desk lamp", "Mug"] }

Always pass a starting value. Without it, reduce uses the first item as the start, which gives the wrong result for objects and throws an error on an empty array.

Chaining them together#

Because map and filter return arrays, you can chain them. This finds the total value of everything in stock:

JavaScript
const stockValue = products
  .filter((product) => product.inStock)
  .map((product) => product.price)
  .reduce((sum, price) => sum + price, 0);
// 2000

Read it from top to bottom: keep the products in stock, take their prices, add them up. A for loop doing the same thing would mix all three steps together.

Which one should I use?#

You want Use You get
The same number of items, changed map A new array, same length
Fewer items filter A new array, same or shorter
One value: a total, an object, a string reduce Anything
The first matching item find One item, or undefined
To check whether any or all items match some, every true or false
To do something without a result, such as logging forEach Nothing

Common mistakes#

  • Forgetting to return. With curly braces, an arrow function needs return: products.map((p) => { p.name }) gives [undefined, undefined, …]. Write (p) => p.name or add return.
  • Using map only for side effects. If you don’t use the array it returns, use forEach or a for...of loop instead.
  • Changing the original objects. products.map((p) => { p.price = 0; return p; }) changes products too. Copy with { ...p, price: 0 }.
  • Using reduce when something simpler fits. A total is a good use. If your reduce is ten lines long, a for...of loop is often easier to read.

Where you’ll use this#

The same three methods appear everywhere: turning CMS items into dropdown options in Wix Velo, rendering lists in React with items.map(...), and shaping data from an API before saving it. They also pair well with async and await when the data comes from a request.

If you need custom code like this on your Wix site, I do Wix Velo development.

Comments