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, I know what you guys are thinking. How hard is this for you?
Answer: I used this reduce and understood that it manipulates the array, but wasn’t aware of this arguments and it’s extensive usage until I went through that interview. Thanks to him!
Well, that’s it.
sayonara