2

I have this sample data:

[{"id":"2", "weeks":2}, {"id":"2", "weeks":4}, {"id":3, "weeks":7}]

I wanted that I will only show one if id is redundant but add all of the weeks that the id's had

My Attempt:

var data = [{"id":"2", "weeks":2}, {"id":"2", "weeks":4}, {"id":3, "weeks":7}];
var weeks = 0;
for (var i=0; i<data.length; i++){
    weeks += data[i].weeks;
}

Desired output

[{"id":"2", "weeks":6}, {"id":3, "weeks":7}]

2 Answers2

3

You can use array#reduce() with Object.values(). Group your data based on id and add the weeks for repeating id in an object. Take the values from the object using Object.values().

const data = [{"id":"2", "weeks":2}, {"id":"2", "weeks":4}, {"id":3, "weeks":7}],
      result = Object.values(data.reduce((r,{id,weeks}) => {
        r[id] = r[id] || {id, weeks : 0};
        r[id].weeks += weeks;
        return r;
      },{}));
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
1

You can Array.prototype.reduce() combined with Array.prototype.push() or Array.prototype.find() based on the number of repeated elements with same id

Code:

const data = [{"id":"2", "weeks":2}, {"id":"2", "weeks":4}, {"id":3, "weeks":7}];
const result = data
  .reduce((a, c) => {
    a.temp[c.id] = ++a.temp[c.id] || 1;
    a.temp[c.id] === 1
      ? a.array.push(c)
      : a.array.find(item => item.id == a.temp[c.id]).weeks += c.weeks;
    return a;
  }, {temp: {}, array: []})
  .array;

console.log(result);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46