开发者问题收集

从数组数组中获取计数

2019-08-22
4664

下面有一个数组数组。使用 ES6,如何将 GoodExcellentWow 的每个值计数放入一个新数组中,例如动态样式的 [{name: Good, count: 4} {name: Excellent, count: 5}, {name:Wow, count:2}] 。我尝试使用 Object.assign ,但无法“唯一”出键加的计数,我需要使用数组,因为我试图在前端呈现它。我需要使用 reduce 吗?怎么样?

let k = 0
const stats = {}
const remarks = [
  [{name: "Good"}],
  [{name: "Good"}, {name: "Excellent"}],
  [{name: "Good"}, {name: "Excellent"}, {name: "Wow"}],
  [{name: "Good"}, {name: "Excellent"}, {name: "Wow"}],
  [{name: "Excellent"}],
  [{name: "Excellent"}]
]

remarks.forEach((arr) => {
  arr.map((e) => {
    Object.assign(stats, { [e.name]: k = k + 1 })
  })
})

console.log(stats);

输出:

stats: {Good: 8, Excellent: 11, Wow: 9}

这是不正确的,而且我需要使用数组。

预期输出:

[{name: Good, count: 4} {name: Excellent, count: 5}, {name:Wow, count:2}]

3个回答

展平数组数组,并从类似这样的对象开始减少它: { 好:0,优秀:0,哇:0

然后 .map 结果的 Object.entries 将其转换为数组:

const remarks = [
  [{ name: "Good" }],
  [{ name: "Good" }, { name: "Excellent" }],
  [{ name: "Good" }, { name: "Excellent" }, { name: "Wow" }],
  [{ name: "Good" }, { name: "Excellent" }, { name: "Wow" }],
  [{ name: "Excellent" }],
  [{ name: "Excellent" }]
];

const result = Object.entries(
  remarks.flat().reduce(
    (all, { name }) => {
      all[name] += 1;
      return all;
    },
    { Good: 0, Excellent: 0, Wow: 0 }
  )
).map(([name, count]) => ({ name, count }));

console.log(result);
Taki
2019-08-22

您可以尝试以下逻辑:

var data = [[{name: "Good"}],[{name: "Good"}, {name:"Excellent"}],[{name: "Good"}, {name:"Excellent"}, {name:"Wow"}],[{name: "Good"}, {name:"Excellent"}, {name:"Wow"}],[{name:"Excellent"}],[{name:"Excellent"}]]

var nData = [];

(data || []).forEach( e => {
  (e || []).forEach(ei => {
    var i = (index = nData.findIndex(d => d.name === ei.name)) >=0 ? index : nData.length;
    nData[i] = {
      name: ei.name,
      count : (nData[i] && nData[i].count ? nData[i].count : 0)+1
    }
  });
});

console.log(nData);

希望这会有所帮助!

Hardik Shah
2019-08-22

您可以使用reduce,然后将结果转换为对象数组:

const counts = remarks.reduce((result, list) => {
  list.forEach(remark => {
    result[remark.name] = (result[remark.name] || 0) + 1;
  });
}, {});
const finalResult = [];
for (let name in counts) {
  finalResult.push({name, count: counts[name]});
}
IceMetalPunk
2019-08-22