François Richard François Richard - 4 years ago 110
Javascript Question

javascript several corresponding array reducing/sumup

What is the cleanest way to reduce those array ?

data = {
id: [1, 1, 1, 3, 3, 4, 5, 5, 5, ...]
v: [10,10,10, 5, 10 ...]
}


For each id there is a v corresponding. What I want is sum up v for each id. In this example the result should be

data = {
id: [1, 3, 4, 5, ...]
v: [30, 15, ...]
}

Answer Source

I would go for the Array.prototype.reduce() ,simple and elegant solution

var ids = [1, 1, 1, 3, 3, 3, 3, 4, 5, 6, 6, 6],
  v = [10, 10, 10, 5, 10, 10, 10, 404, 505, 600, 60, 6],
  data = {};
data.v = [];
data.ids = ids.reduce(function(a, b, index) {
  if (a.indexOf(b) < 0) a.push(b);
  if (!data.v[a.indexOf(b)]) data.v[a.indexOf(b)] = 0;
  data.v[a.indexOf(b)] += v[index];
  return a;
}, []);

https://jsfiddle.net/2ssbngLr/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download