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 ^^

+3


source to share


2 answers


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>
      

Run codeHide result


+4


source


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}]

      



DEMO

+2


source







All Articles