JavaScript map filter & reduce

Nibin Benjamin
2 min readJul 18, 2022

--

Map, reduce and reduce are all JavaScript array functions. All of these functions are higher order functions (takes in another function as an argument). Each of these functions is capable of iterating through an array and perform a transformation or computation.

Array.map

Map function iterates through the provided array and returns a new array. One of the major use-case of map function is in case you need to iterate throughout the array.

Syntax

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

Array.filter

As the name suggests filter function just filters out the provided array. We can write in the condition statement in the callback like so when iteration happens if conditional statement returns true it returns the particular element in the array or else not thereby filtering the array. Its more understandable from the snippet below

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

In the callback function we can see condition provided

item % 2 === 0

So only if the condition is true, the particular array item is returned. So above code returns only even numbers.

Array.reduce

Reduce function reduces the provided array into a single value. The output is derived from running a reducer function on each element in the array.

Syntax

arr.reduce(reducerFunction, initialValue])

reducerFunction function takes in 4 arguments:

  1. Accumulator — the returned value from previous iteration.
  2. Current Value
  3. Current Index
  4. Array — the original array on which reduce function was called.
const numbers = [10, 20, 30, 40];
const sum = numbers.reduce(function (result, item) {
return result + item;
}, 0);
console.log(sum); // 100

Another use case of reduce where we update the passed array.

const nums = [1,2,3,4];nums.reduce((a, c, i, arr) => arr[i] += a, 0);console.log(nums); // [1,3,6,10]

--

--

No responses yet