Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding duplicates in array of objects javascript [duplicate]

I have an array of objects that looks like the following:

            {value: 20, color: 'F88C00'},
            {value: 40, color: 'D8605F'},
            {value: 20, color: '72C380'},
            {value: 20, color: '2C7282'},
            {value: 20, color: '72C380'}

I want to use javascript/jquery to loop through them to check if there are any duplicates in the color column, and if there are duplicates, here '72C380' occurs twice. Then there should be only one entry but their values should be summed.

Desired Output:

            {value: 20, color: 'F88C00'},
            {value: 40, color: 'D8605F'},
            **{value: 40, color: '72C380'},**
            {value: 20, color: '2C7282'}

I know how to do that in python, but not JS

like image 343
Rahul Bhatia Avatar asked Jun 18 '14 05:06

Rahul Bhatia


1 Answers

You can use a temp map like this

var array = [{
    value: 20,
    color: 'F88C00'
}, {
    value: 40,
    color: 'D8605F'
}, {
    value: 20,
    color: '72C380'
}, {
    value: 20,
    color: '2C7282'
}, {
    value: 20,
    color: '72C380'
}];

var op = [],
    map = {}, it, item;
for (var i = 0; i < array.length; i++) {
    it = array[i];
    item = map[it.color];
    if (item) {
        item.value += it.value;
    } else {
        map[it.color] = item = {
            value: it.value,
            color: it.color
        };
        op.push(item);
    }
}
console.log(op)

Demo: Fiddle

like image 183
Arun P Johny Avatar answered Sep 28 '22 01:09

Arun P Johny