总结数组的特定对象

时间:2018-08-20 00:39:02

标签: javascript lodash

我有一个像这样的数组

var array = [
{occurrences: 1, position: "1"},
{occurrences: 4, position: "2"},
{occurrences: 1, position: "1"},
{occurrences: 2, position: "3"},
];

我想这样总结:

{occurrences: 2, position: "1"},
{occurrences: 4, position: "2"},
{occurrences: 2, position: "3"}

我可以使用lodash或其他方法实现吗?

1 个答案:

答案 0 :(得分:1)

不需要Lodash,就像在this answer中一样,您需要遍历数组并构造一个新的结果数组:

var result = [];
var array = [{
    occurrences: 1,
    position: "1"
  },
  {
    occurrences: 4,
    position: "2"
  },
  {
    occurrences: 1,
    position: "1"
  },
  {
    occurrences: 2,
    position: "3"
  },
];

array.reduce(function(res, value) {
  if (!res[value.position]) {
    res[value.position] = {
      occurrences: 0,
      position: value.position
    };
    result.push(res[value.position])
  }
  res[value.position].occurrences += value.occurrences
  return res;
}, {});

console.log(result);
/*
Will print:

[
  {
    "occurrences": 2,
    "position": "1"
  },
  {
    "occurrences": 4,
    "position": "2"
  },
  {
    "occurrences": 2,
    "position": "3"
  }
]

*/