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.
|
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:
- Loop through the array of objects
- Check if the customer name is already present in the finalResult array
- f the customer name is not present in the finalResult array, then add the customer name and the order amount to the finalResult array
- 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:
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.
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:
Those are three ways I can think of currently, Kindly leave your comment if you have a better way of doing this.
Happy coding!
Post a Comment
0Comments