Concatenate array object together - lodash
So, I have an array of items like this:
items = [
{
amount: 2,
name: 'bike'
},
{
amount: 1,
name: 'boat'
},
{
amount: 3,
name: 'bike'
}
]
Now I would like to merge this array so that there are no duplicate bike and still know how many bikes there are.
so my result array will look like this:
items = [
{
amount: 5,
name: 'bike'
},
{
amount: 1,
name: 'boat'
}
]
To keep the code shorter, I was advised to use lodash
and considered various ways to combine arrays. But to be honest, it is quite difficult to figure out what would be the best approach, so I ask you guys ^^
source to share
You can use .groupBy
with .map
and _.sum
to calculate amount
, for example
var items = [{
amount: 2,
name: 'bike'
}, {
amount: 1,
name: 'boat'
}, {
amount: 3,
name: 'bike'
}];
var res = _(items)
.groupBy('name')
.map(function (el, name) {
return {
name: name,
amount: _.sum(el, 'amount')
};
})
.value();
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.7.0/lodash.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
source to share
If you don't want to load lodash
in specifically for this example (not sure if the extra 50K is worth your space here for a few extra lines of code), here's a vanilla version of JS that uses a temporary object to hold values while looping over various objects:
function merge(items) {
var tmp = {}, out = [];
for (var i = 0, l = items.length; i < l; i++) {
var name = items[i].name;
var amount = items[i].amount;
if (!tmp[name]) tmp[name] = 0;
tmp[name] += amount;
}
for (var p in tmp) {
out.push({ name: p, amount: tmp[p] });
}
return out;
}
merge(items); // [{"name":"bike","amount":5},{"name":"boat","amount":1}]
source to share