我有一个具有重复次数的数组。我想得到重复的次数。 我的数组是这样的:
var array = [
{ asset: "A", sector: "Hospital" },
{ asset: "B", sector: "Hardware" },
{ asset: "C", sector: "Networking" },
{ asset: "D", sector: "Networking" },
{ asset: "E", sector: "Food" },
{ asset: "F", sector: "Hospital" },
{ asset: "G", sector: "Hardware" },
{ asset: "H", sector: "Industrial" },
{ asset: "I", sector: "Transport" },
{ asset: "J", sector: "Hardware" },
{ asset: "K", sector: "Networking" },
{ asset: "L", sector: "Transport" }
]
现在,我希望重复次数也按如下排序顺序进行计数:
final_array = [
{ sector: 'Hardware', count: 3 },
{ sector: 'Networking', count: 3 },
{ sector: 'Hospital', count: 2 },
{ sector: 'Transport', count: 2 },
{ sector: 'Food', count: 1 },
{ sector: 'Industrial', count: 1 }
]
我不知道从哪里可以知道这件事。我有很多链接,但是它们解决了数组下而不是对象数组上的重复。
我使用一种方法,但不能解决我的问题
var finalD = [];
c.forEach(x => {
if (isSectorExists(x.sector, finalD) == true) {
//Here I don't know how I will increase the counter.
} else {
finalD.push({ sector: x.sector, count: 1 });
}
});
var isSectorExists = (sector, arr) => {
return arr.some(function(el) {
return el.sector === sector;
});
};
我知道我的方法很长。是否有人拥有执行此类任务的最佳简便方法。真的很感谢任何帮助。在此先感谢
答案 0 :(得分:0)
您可以构建一个以扇区名称作为键的对象counts
,并以计数的形式存储计数的对象,遍历数组并更新这些计数,然后最终获得该counts
对象的值
var array = [
{ asset: "A", sector: "Hospital" },
{ asset: "B", sector: "Hardware" },
{ asset: "C", sector: "Networking" },
{ asset: "D", sector: "Networking" },
{ asset: "E", sector: "Food" },
{ asset: "F", sector: "Hospital" },
{ asset: "G", sector: "Hardware" },
{ asset: "H", sector: "Industrial" },
{ asset: "I", sector: "Transport" },
{ asset: "J", sector: "Hardware" },
{ asset: "K", sector: "Networking" },
{ asset: "L", sector: "Transport" }
];
var counts = array.reduce((m, c) => {
if (c.sector in m) m[c.sector].count += 1;
else m[c.sector] = { sector: c.sector, count: 1};
return m;
}, {});
let finalArray = Object.values(counts).sort((a, b) => b.count - a.count);
console.log(finalArray);
这将获得线性时间的计数(而不是为每个元素调用isSectorExists
使其成为 O(n ^ 2)。