Javascript is so amazing to learn. I learn few things on the fly to fix some error or try {} catch way (basically fail and understand better). One among them is this.reduce();
.
this.reduce()
takes array and gives back single value. Let's take an example
Before going further to understand about reduce, let's take a look at it's arguments. Reduce takes 4 arguments.
- total //!req a + b, it returns either initial value or summed value
- currentValue //!req value of the current element
- currentIndex //!opt
- arr //!opt array
Example with just number of arrays
let arr = [1, 2, 3, 4, 5, 6];
let ans = arr.reduce( (a, b) => a + b ); // 21
Example with objects
let movies = [{ title: 'Cars', part: '1', views: '400' },
{ title: 'Cars', part: '2', views: '300' },
{ title: 'Cars', part: '3', views: '100' },
{ title: 'Planes', part: '1', views: '800' },
{ title: 'Planes', part: '2', views: '500' }];
let total = { cars: 0, planes: 0 };
let totalviewsmovies = movies.reduce( (a, b) => {
total[b.title.toLowerCase()] += parseInt(b.views, 10);
});
console.log( total ); // { cars: 400, planes: 1300 }
Okay, there might be a question? How this is hard for you?.
Answer: I didn't know this much detail of arguments and how it works until I recently got interviewed in some company.
Thanks to him!
Let me know what you think.
Top comments (0)