Ordering, Grouping by Key and Sum An Array of Objects in JavaScript

group-by-key-sum-array-oobject-javascript

 

I was recently required to group an array of objects by key and sum the amount so that there will be no duplicates. For clarity, given an array of orders objects like the one on the left, we are to return the result like what we have on the right.

array-of-orders



Add More Traffic

Grouping and Summing the arrays

We are going to solve this issue in three different ways. Let's dive into solving this.

Method 1

Let's list out the step we will take to implement the first method:
  1. Loop through the array of objects
  2. Check if the customer name is already present in the finalResult array
  3. f the customer name is not present in the finalResult array, then add the customer name and the order amount to the finalResult array
  4. If the customer name is already present in the finalResult array, then add the order amount to the existing amount
Here is how this is implemented in code:

group-sum-javascript-using-loop


Method 2

We will use array reduce in this second method, just like the first method, we will check for object existence and also update them accordingly. The code below shows how this is done.

group-sum-javascript-using-reduce



Method 3

The third method also involved looping through the array of objects and adding the current object in the resultArray if it is not in the Map else update it if it already exists like so:

group-sum-javascript-using-map


Those are three ways I can think of currently, Kindly leave your comment if you have a better way of doing this.

Happy coding!







No comments:

Powered by Blogger.