DEV Community

Prasanna Vijayan
Prasanna Vijayan

Posted on • Edited on

How did I learn this.reduce();

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.

  1. total //!req a + b, it returns either initial value or summed value
  2. currentValue //!req value of the current element
  3. currentIndex //!opt
  4. 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

Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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)