JavaScript Map, Reduce, and Filter: What, Why and How to use it

JavaScript Map, Reduce, and Filter: What, Why and How to use it

Map, reduce, and filter are all array methods in JavaScript. In this JavaScript tutorial, you will learn what, why and how to use each one. Learn eight methods to iterate through an array in JavaScript! Methods include: forEach, map, filter, reduce, some, every, find, findIndex. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function

JavaScript Map, Reduce, and Filter - Explained with Examples

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why and how to use each one.

Here is a fun summary by Steven Luscher:

Map/filter/reduce in a tweet:

map([๐ŸŒฝ, ๐Ÿฎ, ๐Ÿ”], cook) => [๐Ÿฟ, ๐Ÿ”, ๐Ÿณ]

filter([๐Ÿฟ, ๐Ÿ”, ๐Ÿณ], isVegetarian) => [๐Ÿฟ, ๐Ÿณ]

reduce([๐Ÿฟ, ๐Ÿณ], eat) => ๐Ÿ’ฉ

Map

The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.

Syntax

var new_array = arr.map(function callback(element, index, array) {
    // Return value for new_array
}[, thisArg])

In the callback, only the array element is required. Usually some action is performed on the value and then a new value is returned.

Example

In the following example, each number in an array is doubled.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]

Filter

The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

Syntax

var new_array = arr.filter(function callback(element, index, array) {
    // Return true or false
}[, thisArg])

The syntax for filter is similar to map, except the callback function should return true to keep the element, or false otherwise. In the callback, only the element is required.

Examples

In the following example, odd numbers are "filtered" out, leaving only even numbers.

const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]

In the next example, filter() is used to get all the students whose grades are greater than or equal to 90.

const students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
];

const studentGrades = students.filter(student => student.grade >= 90);
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]

Reduce

The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.

Syntax

arr.reduce(callback[, initialValue])

The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

  • accumulator - the returned value of the previous iteration
  • currentValue - the current item in the array
  • index - the index of the current item
  • array - the original array on which reduce was called
  • The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.

Examples

The following example adds every number together in an array of numbers.

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {
  return result + item;
}, 0);
console.log(sum); // 10

In the next example, reduce() is used to transform an array of strings into a single object that shows how many times each string appears in the array. Notice this call to reduce passes an empty object {} as the initialValue parameter. This will be used as the initial value of the accumulator (the first argument) passed to the callback function.

var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

var petCounts = pets.reduce(function(obj, pet){
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
}, {});

console.log(petCounts); 

/*
Output:
 { 
    dog: 2, 
    chicken: 3, 
    cat: 1, 
    rabbit: 1 
 }
 */

JavaScript WebDev javascript

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

What is โ€œthisโ€ in Javascript? | Explaining this keyword in Javascript!

In this JavaScript tutorial, we will learn about what is โ€œthisโ€ keyword in JavaScript. You'll understand this and its mechanism, in depth. The this keyword in JavaScript has often been a source of much confusion for beginners to the language.

Building a Powerful Virtual Machine in JavaScript

This JavaScript tutorial explains how to build a powerful Virtual Machine in JavaScript. A flexible, extensible, register-based virtual machine. Support for signed, unsigned and floating point operations. A call stack. Interrupt capabilities. Ability to do memory mapping for IO. An assembly language with macro and module support. A higher level, C like language. We'll use and expand the library from the parser combinators from scratch series. And finally, to be able to take the whole thing into the browser and exend it to create a sort of fantasy console - an emulator for a machine that never existed

Understanding JavaScript Decorators

Decorators are actually nothing more than functions that return another function, and that are called with the appropriate details of the item being decorated. Using decorators in your projects today requires some transpiler configuration. What is a Decorator? JavaScript Decorators and Property Descriptors. How to Write a Decorator. Handling API Errors. Decorating Classes. A Babel Workaround