Assume we have an array of objects - baskets with fruits.
const fruits = [
{
apples: 4,
pears: 6,
oranges: 2,
},
{
bananas: 2,
oranges: 5,
},
{
pears: 8,
apples: 3,
bananas: 10,
},
{},
{
pears: 7,
apples: 5,
},
{
mangos: 1,
},
];
There are different types of fruits with different quantities in each basket (one basket even empty).
How can we merge all these objects (baskets) into one and count total sum of each fruit?
Let’s create helper method.
const mergeFruits = data => {
const result = {}; //(1)
data.forEach(basket => { //(2)
for (let [key, value] of Object.entries(basket)) { //(3)
if (result[key]) { //(4)
result[key] += value; //(5)
} else { //(6)
result[key] = value;
}
}
});
return result; //(7)
};
- Result object, empty.
- Loop through an array of objects using Array.prototype.forEach() method.
- Iterate over each object's (basket's) key-value pairs using Object.entries() method.
- Check if the result object has a property with the name of the key.
- If yes (true), add to the previous value of the property the value of the key, e.g. if there is a property “apples” with value “4” in the result object, then add more apples from the next basket.
- If no (false), then it’s a new property (a new fruit) for a result object, so create this property and assign the corresponding value to it.
- Return merged object
If we run the code and print the result into console:
const mergedObject = mergeFruits(fruits);
console.log(mergedObject);
we’ll get the following output:
{ apples: 12, pears: 21, oranges: 7, bananas: 12, mangos: 1 }
All objects (baskets) in the array merged into one with the sum of each property’s (fruit) value.
Originally posted on my own blog
Top comments (9)
No need to reinvent the wheel; you can just use
Array.reduce
:What you did is the same thing, but without taking advantage of reduce.
Good point! Thanks!
But I think it's good to have different solutions of the same problem;)
Definitely! Your solution demonstrates how Array.reduce would work under the hood for this problem, so it's no "bad" per se.
I think
Array.reduce
is more like recursive function, rather than taking advantage of mutability.This is right on the money. There’re certain times when mutating things makes sense, and others when generating a new array with reduce is a better choice. It’s all about knowing when to use the right tool.
Javascript is just so confusing. We implement new functions without even knowing there is a built in method for this solution.
I guess I just learn something new every day
This is exactly the solution I was looking for, and Aleksandr's response is great too.
Thank you to both of you!
Thank you!
I use
lodash
library