Clean Markup

Mastering Array Map Filter and Reduce in JavaScript

Mastering Array Map Filter and Reduce in JavaScript

Imperative for loops that push items into external temporary arrays and mutate counters often obscure the true intent of your code. By using JavaScript's built-in higher-order array methods—filter, map, and reduce—you can transform raw API responses into UI view models through pure, composable pipelines without mutating the original array.

Example

Given a list of blog posts, suppose we want to calculate the total reading time of all published javascript articles and return their formatted titles:

Input:
[
  { title: "Two Sum", tag: "javascript", minutes: 5, published: true },
  { title: "Draft CSS", tag: "css", minutes: 4, published: false },
  { title: "Debounce", tag: "javascript", minutes: 7, published: true }
]

Output:
{
  titles: ["Two Sum (5 min)", "Debounce (7 min)"],
  totalMinutes: 12
}

Input : Array of article objects
Output : Filtered, transformed, and aggregated summary object without mutating the input array.

Implementation

var articles = [
  { title: "Two Sum", tag: "javascript", minutes: 5, published: true },
  { title: "Draft CSS", tag: "css", minutes: 4, published: false },
  { title: "Debounce", tag: "javascript", minutes: 7, published: true },
  { title: "Semantic HTML5", tag: "html", minutes: 6, published: true }
];

function summarizeCategory(items, targetTag) {
  // 1. Filter only published articles matching the target tag
  var matching = items.filter(function (item) {
    return item.published && item.tag === targetTag;
  });

  // 2. Map each article to a formatted display label
  var titles = matching.map(function (item) {
    return item.title + " (" + item.minutes + " min)";
  });

  // 3. Reduce matching articles to their total reading time
  var totalMinutes = matching.reduce(function (sum, item) {
    return sum + item.minutes;
  }, 0);

  return {
    titles: titles,
    totalMinutes: totalMinutes
  };
}

console.log(summarizeCategory(articles, "javascript"));
// { titles: [ 'Two Sum (5 min)', 'Debounce (7 min)' ], totalMinutes: 12 }

Main Point: Always pass an explicit initial value (such as 0 or {}) as the second argument to Array.prototype.reduce so your code handles empty arrays safely without throwing a TypeError.

Credits

Photo by Chris Ried

← Home