Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 26, 2020 11:25 pm GMT

JavaScript - Map, Filter, and Reduce

Map, filter, and reduce are three useful functions which can help to simplify your JavaScript code.

Below is a simple data structure which we will reference as we learn about these functions.

const people = [    {        age: 25,        name: "Jane"    },    {        age: 30,        name: "Joe"    },    {        age: 35,        name: "John"    }];
Enter fullscreen mode Exit fullscreen mode

Let's say that we just needed a collection of peoples ages; there are numerous ways to do this. The following is a common solution.

const ages = [];for (const person of people) ages.push(person.age);// [25,30,35]
Enter fullscreen mode Exit fullscreen mode

Map allows us to simplify the solution quite a bit.

const ages = people.map(person => person.age);// [25,30,35]
Enter fullscreen mode Exit fullscreen mode

Here, we pass a callback to map, and for each element within the collection, we determine what we want to return.

Now, what if we need to create a collection comprised only of people over the age of 30? We could do something like the following.

const peopleOverThirty = [];for (const person of people) {    if (person.age > 30) peopleOverThirty.push(person);}// [{age: 35, name: "John"}]
Enter fullscreen mode Exit fullscreen mode

Now, let's see how filter can be used to produce the same result.

const peopleOverThirty = people.filter(person => person.age > 30);// [{age: 35, name: "John"}]
Enter fullscreen mode Exit fullscreen mode

Similar to map, we pass filter a callback, here however, rather than what we want to return, we determine which elements to return using a conditional statement.

Next, let's get a sum of every person's age. Assuming that we have our ages array from earlier, below would be one way to achieve this.

let ageSum = 0;for (const age of ages) ageSum += age;// 90
Enter fullscreen mode Exit fullscreen mode

Here's the solution using reduce.

const ageSum = ages.reduce((acc, age) => acc + age);// 90
Enter fullscreen mode Exit fullscreen mode

As per usual, we pass the function a callback, although we're giving our callback two arguments this time. The first argument is the accumulator, which is going to hold the result of each consecutive operation. The second argument is the current element, as with map and filter.

These are small examples of how map, filter, and reduce can help to keep your code simple.


Original Link: https://dev.to/brandonmweaver/javascript-map-filter-and-reduce-22jb

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To