A Quick Overview of map(), filter(), and reduce() in JavaScript

Image by Nathan Dumlao

Learn how to use map, filter, and reduce in JavaScript.

Higher Order Functions

A higher-order function is a function that takes one or more functions as arguments or returns a function as its result. map, filter, andreduce are all higher order functions, which take a function as an argument.

Map, Filter, Reduce Fundamentals

All the functions are part of the JavaScript Array prototype which means they must be called directly on an array.

const arr = [1, 2, 3]
arr.map()
arr.filter()
arr.reduce()

When we are using map,filter, and reduce, we cannot:

  • break the loop
  • use continue

map → Executes a function on each element of an array

Every element of the array is passed to the callback function and returns a new array with the same length.

When to use map: If we want to perform the same operation/transformation on each element of the array and get back a new array of the same length with the transformed values.

Example 1 :

var numbers= [1,2,3,4,5];
var doubled  = numbers.map(n => n * 2);
doubled; // [2,4,6,8,10]

filter → Remove items which don’t satisfy a condition

Every element of the array is passed to the callback function. On each iteration, if the callback returns true, then that element will be added to the new array, otherwise, it is not added to the new array.

var numbers = [1,2,3,4,5];
var greaterThan2 = numbers.filter(n => n > 2);
greaterThan2; // [3,4,5]

Reduce → Creates a single value from elements of Array

While using reduce, we need to declare the initial value of accumulator(final result). On each iteration, inside the callback we perform some operation and that will be added to the accumulator.

Example 1: Sum of numbers

var numbers = [1,2,3,4,5];
var initialVal = 0;
let result=numbers.reduce((accu, val) => val + accu , initialVal);
console.log(result) // 15

Example 2: Creating an array of objects from user names

https://gist.github.com/Jagathishrex/7261bcc6cae88a629fd28759ac119805#file-reduce-js

Real-world example

Let’s create a real-world practical example: Conducting an Interview

  • map: Conducting a test for multiple candidates
  • filter: Selecting candidates who passed the test
  • reduce: Creating a team from the selected candidates

https://gist.github.com/Jagathishrex/3ee5f85a69d31a723cbead54d13afec8#file-map_filter_reduce-js

Join your hand🖐 with me Javascript Jeep🚙💨.

Buy me a coffee

Buy me a coffee

Leave a comment

Design a site like this with WordPress.com
Get started