How did I learn this.reduce();

prasannavijayan

Prasanna Vijayan

Posted on September 15, 2019

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.

💖 💪 🙅 🚩
prasannavijayan
Prasanna Vijayan

Posted on September 15, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024