Isaac
asked on
Object array add values
Can someone help me with this javascript?
It's supposed to remove duplicates from an object array and add the values left.
http://jsfiddle.net/9vyuY/1/
It's supposed to remove duplicates from an object array and add the values left.
http://jsfiddle.net/9vyuY/1/
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
For future reference, this is the working code
var foo = [ { "a" : 15 }, { "b" : 25 }, { "a" : 15 }, {"c" : 13} ];
var uniqBy = function(ary, key) {
var seen = {};
return ary.filter(function(elem) {
var k = key(elem);
return (seen[k] === 1) ? 0 : seen[k] = 1;
})
}
uniqs = uniqBy(foo, JSON.stringify);
values = uniqs.map(function(x) { for(var k in x) return x[k] });
sum = values.reduce(function(a, b) { return a + b });
alert(sum);
ASKER