javascript - how to group objects in an array -
i have array of objects , want group objects on basis of 2 keys
var arr = [ {"name": "apple", "id": "apple_0","c":'20'}, {"name": "dog", "id": "dog_1","c":'10'}, {"name": "apple", "id": "apple_0","c":'30'}, {"name": "dog", "id": "dog_1","c":'10'}, ];
and expecting result as
var final = [ {"name": "apple", "id": "apple_0","c":'50'}, {"name": "dog", "id": "dog_1","c":'20'} ];
the scenario - want group object on basis of name
, id
. if name
, id
found in final array make sum of c
.
i tried this:
var final = []; for(var = 0; i<arr.length; i++){ var obj = {}; obj = arr[i]; for(var j = 0; j<final.length; j++){ if((obj[name] !== final[j].name) && (obj[id] !== final[j].id)){ final.push(obj) }else{ //addition of key `c` in existing object in `final` array } } }
but inner loop not working , hanging system due continuous loop execution.
please let me know how fix or other logic final result.
here solution using hash table
, #reduce()
function - see demo below:
var arr = [{"name": "apple", "id": "apple_0","c":'20'},{"name": "dog", "id": "dog_1","c":'10'}, {"name": "apple", "id": "apple_0","c":'30'},{"name": "dog", "id": "dog_1","c":'10'}]; var result = arr.reduce(function(hash){ return function(p,c){ if(hash[c.id]) hash[c.id].c = +hash[c.id].c + +c.c else { hash[c.id] = hash[c.id] || c; p.push(hash[c.id]); } return p; } }(object.create(null)), []); console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
Comments
Post a Comment