Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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

share|improve this question

marked as duplicate by Dalorzo, Bhushan Kawadkar, cookie monster, Code Lღver, Huangism Jun 18 at 14:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Do you want to delete it? –  Kermani Jun 18 at 5:32
    
I want to delete the duplicate ones but add upp the values –  Rahul Bhatia Jun 18 at 5:39

2 Answers 2

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

share|improve this answer

console it ...

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


var colors = [];
var result = collection;
$.each(result, function(i, item){ 
  if(colors.indexOf(item.color)!= -1){ 
      $.each(result,function(f, find){
        if(find.color == item.color){
          result[f].value += item.value;
        }
      })
      delete result[i];
  }else{
     colors.push(item.color);  
  } 
})
var colors = [];
console.log(result);
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.