Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 would be no duplicates of bike and still know how many bikes there are in total.

so my result array would look like this:

items = [
    {
        amount: 5,
        name: 'bike'
    },
    {
        amount: 1,
        name: 'boat'
    }
]

In order to keep my code short I have been advised using lodash and I've been looking at the different ways to merge arrays together. But to be honest it quite confusing to figure out what the best approach would be, which is why I'm asking you guys ^^

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
759 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use .groupBy with .map, and _.sum for calculate amount, like so

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...