How to merge two arrays of objects, and sum the values of duplicate object keys in JavaScript? -


so, have indeterminate amount of arrays in object, , need merge objects in them. arrays guaranteed same length, , objects guaranteed have same keys.

i've tried iterating through it, though reason, sums objects in every key in array.

example:

var demo = {   "key1": [{"a": 4, "b": 3, "c": 2, "d": 1}, {"a": 2, "b": 3, "c": 4, "d": 5}, {"a": 1, "b": 4, "c": 2, "d": 9}]   "key2": [{"a": 3, "b": 5, "c": 3, "d": 4}, {"a": 2, "b": 9, "c": 1, "d": 3}, {"a": 2, "b": 2, "c": 2, "d": 3}] };  mergearrays(demo);  /* returns:   {     "arbitraryname": [{"a": 7, "b": 8, "c": 5, "d": 5}, {"a": 4, "b": 12, "c": 5, "d": 8}, {"a": 3, "b": 6, "c": 4, "d": 12}]   } */ 

my current implementation attempts this:

var skeleton = {   "a": 0,   "b": 0,   "c": 0,   "d": 0 };  function mergearrays = function (obj) {   var flat = {};   var keys = _.keys(prod);   var len = obj[keys[0]].length;   flat["arbitraryname"] = [];   (var = 0; < len; i++) {     flat["arbitraryname"].push(skeleton);   }   flat["arbitraryname"].foreach(function (v, k) {     _.forin(v, function (key, value) {       flat["arbitraryname"][k][key] += value;     });   });   return flat; } 

is there easier way that? appears return array right that's entirely identical. e.g.:

[{"a": 14, "b": 26, "c": 14, "d": 25}, {"a": 14, "b": 26, "c": 14, "d": 25}, {"a": 14, "b": 26, "c": 14, "d": 25}] 

where each object sum of elements in array. doing wrong? there easier way?

the following matches commented array @ top of question. expected results little unclear

using object.keys() makes easy.

var demo = {      "key1": [{"a": 4, "b": 3, "c": 2, "d": 1}, {"a": 2, "b": 3, "c": 4, "d": 5}, {"a": 1, "b": 4, "c": 2, "d": 9}],      "key2": [{"a": 3, "b": 5, "c": 3, "d": 4}, {"a": 2, "b": 9, "c": 1, "d": 3}, {"a": 2, "b": 2, "c": 2, "d": 3}]  };    // iterate , map using first array  var res = demo.key1.map(function(item, idx) {       //  loop on keys of each object in array , return       //  new objects sums of matching index , keys      return object.keys(item).reduce(function(obj,key) {          obj[key] = item[key] + demo.key2[idx][key];          return obj;      },{});    });    // print "res" demo  document.getelementbyid('pre').innerhtml =json.stringify(res, null, 4)
<pre id="pre"></pre>


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -