map, reduce, filter: Use newer array methods like a Pro.

map, reduce, filter: Use newer array methods like a Pro.

Arrays are the most used data structure in the programming world. The newer array methods like map(), reduce() and filter() are extensively used in building projects using some library/ framework like React/Vue/ Angular.

In this blog post, I will be talking about these methods in great detail with real-world examples.

Let us begin -

1. map()

  • Array.map() creates a new array with the elements returned by the callback function passed to it.

  • This callback function is executed for every element in the array and a returned value is expected from it.

  • If nothing is returned from the callback function then undefined will be returned implicitly and get stored in the newly created array.

  • The length of the new array is exactly equal to the one on which map() was called.

  • It doesn't change the original array.

So much of talk, let's see an example.

const nums = [1,3,5,7];

const numsDoubled = nums.map(number => number *2);
console.log(numsDoubled);  // [2, 6, 10, 14]

// No return from map's callback fn
const undefArray = nums.map(number => {
            let double = nums*2;
});
console.log(undefArray); // [undefined, undefined, undefined, undefined]

2. reduce()

Array.reduce( ) method takes a reducer function (provided by us), executes this reducer function for every element in the Array, and results in a single value.

Let us look at a simple example first.

Assume we have an Array of marks obtained by a student & it's required to calculate the total marks scored.

const studentMarks = [65,75,63,58,69];
const totalMarks = studentMarks.reduce((accumulator, currentElement) => accumulator + currentElement);

console.log(totalMarks); // 330

Let's understand how the above code works -

In the first iteration

  1. The accumulator(acc) value is initialized with the first element of the array (65 in this case)
  2. The currentElement is 75 (the 2nd element of array),in the 1st iteration.
  3. accumulator + currentElement,65 + 75 =140 is returned & assigned to accumulator

In the 2nd iteration

  1. accumulator value has become 140 (equal to the result of the first iteration)
  2. the currentElement is 63 i.e. the next element of the array from the previous iteration.
  3. Again,accumulator + currentElement,140 + 63 = 203 is returned & assigned to accumulator

This continues until the Array is exhausted. Once there is no further element to iterate over, the accumulator value is returned and stored in the totalMarks variable.

Let's look at another variant of Array.reduce( )

Consider a scenario,

The principal of the school decided to give 20 grace marks to the student, acknowledging the fact that the classes were not held properly due to the coronavirus pandemic.

How the .reduce( ) function tackles this situation? See the code below;

const studentMarks = [65,75,63,58,69];
const totalMarks = studentMarks.reduce((acc, currentElement) => acc + currentElement, 20);

console.log(totalMarks); // 350

it turns out, Array.reduce( ) can take the 2nd parameter (it's optional ) as the initial value for the accumulator.

  1. If we pass 2nd argument to .reduce( ) then the accumulator's initial value is set as the argument passed & the currentElement starts from 1st element , 65 in this case

  2. If we don't pass 2nd argument then the accumulator value is initialized with the first value of the array (65 in this case) and the currentElement is 75 (the 2nd value of the array) as explained in the first example.

filter

Array.filter() method creates a new array with the elements for which the provided function to filter() returns true.

Like map(), filter() doesn't change the original array too.

See Example below -

const array = [1,-1,2,3,-5];
const positiveArray = array.filter(num => num >= 0);
console.log(positiveArray) // [1, 2, 3]

Notice that the function returns true when num is greater than or equal to zero.

Summary

  • map, reduce and filter are widely used in working with library/framework.

  • None of these methods alter the original array.

  • map() and filter() results a new array, whereas reduce() results in a single value.

If you got any questions or doubt, feel free to ping me on Twitter.

twitter.com/faheem_khan_dev

I hope it was a great read for you. If you have any feedback please share it in the comment below.

Did you find this article valuable?

Support Faheem Khan by becoming a sponsor. Any amount is appreciated!