1
var data = [
  { row: 'aa', col: 1, value: 1 },
  { row: 'bb', col: 2, value: 1 },
  { row: 'bb', col: 3, value: 1 },
  { row: 'aa', col: 1, value: 1 },
  { row: 'aa', col: 2, value: 1 }
]

var o = {}
var result = data.reduce(function(r, e) {
  var key = e.row + '|' + e.col;
  if (!o[key]) {
    o[key] = e;
    r.push(o[key]);
  } else {
    o[key].value += e.value;
  }
  return r;
}, []);

console.log(result)

RESULT I GET:

0: {row: "aa", col: 1, value: 2}
1: {row: "bb", col: 2, value: 1}
2: {row: "bb", col: 3, value: 1}
3: {row: "aa", col: 2, value: 1}

RESULT I WANT: How to combine row togheter and sum the col and value so output be this:

RESULT:
0: {row: "aa", col: 3, value: 3}
1: {row: "bb", col: 5, value: 2}

here is the jsFiddle: https://jsfiddle.net/kpj29uv6/

1 Answer 1

1

SOLVED!

var data = [
  { row: 'aa', col: 1, value: 1 },
  { row: 'bb', col: 2, value: 1 },
  { row: 'bb', col: 3, value: 1 },
  { row: 'aa', col: 1, value: 1 },
  { row: 'aa', col: 2, value: 1 }
]

var o = {}
var result = data.reduce(function(r, e) {
    r[e.row] = r[e.row] || { row: e.row, col: 0, value: 0 };

  r[e.row].col += e.col;
  r[e.row].value += e.value;

  return r;
}, {});

console.log(Object.values(result));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.