DEV Community

Prasanna Vijayan
Prasanna Vijayan

Posted on β€’ Edited on

2

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)

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay