繁体   English   中英

如何找到对象数组中出现次数最多的项目?

[英]How can I find the highest occurrence of an item in an array of objects?

我有一个对象数组,我想在每个 object 中找到一个项目的最高出现频率并返回频率:

var arr = [{spot_id: 6, spot_no: 6, gate_id: 6}, {spot_id: 16, spot_no: 17, gate_id: 5}, {spot_id: 5, spot_no: 5, gate_id: 5}, {spot_id: 11, spot_no: 11, gate_id: 5}, {spot_id: 15, spot_no: 16, gate_id: 4}, {spot_id: 4, spot_no: 4, gate_id: 4}, {spot_id: 10, spot_no: 10, gate_id: 4}, {spot_id: 14, spot_no: 15, gate_id: 3}, {spot_id: 9, spot_no: 9, gate_id: 3}, {spot_id: 3, spot_no: 3, gate_id: 3}, {spot_id: 8, spot_no: 8, gate_id: 2}, {spot_id: 13, spot_no: 14, gate_id: 2}, {spot_id: 2, spot_no: 2, gate_id: 2}, {spot_id: 7, spot_no: 7, gate_id: 1}, {spot_id: 12, spot_no: 13, gate_id: 1}];

我试图找到使用此代码,但它返回一个 object,每个字段的值为 1、1、1:

var items = arr.sort((a, b) =>
  arr.filter(v => v.gate_id === a.gate_id).length -
  arr.filter(v => v.gate_id === b.gate_id).length
).pop();

我希望它返回在这个数组中出现的最高的gate_id5,5,54,4,43,3,32,2,2 ,基本上只是其中之一,我不在乎一,我想返回频率,在这种情况下频率是3倍。

找到了解决方案。

下面我找到所有值的出现(gate_id):

var result = array.reduce( (acc, o) => (acc[o.gate_id] = (acc[o.gate_id] || 0)+1, acc), {} );

在这里我找到了所有事件中的最高值:

const max = Math.max.apply(null, Object.values(result));

此代码将返回特定值的最大出现次数。 在这个例子中它是 3。我保持代码简单希望这有帮助

 var arr = [{spot_id: 6, spot_no: 6, gate_id: 6}, {spot_id: 16, spot_no: 17, gate_id: 5}, {spot_id: 5, spot_no: 5, gate_id: 5}, {spot_id: 11, spot_no: 11, gate_id: 5}, {spot_id: 15, spot_no: 16, gate_id: 4}, {spot_id: 4, spot_no: 4, gate_id: 4}, {spot_id: 10, spot_no: 10, gate_id: 4}, {spot_id: 14, spot_no: 15, gate_id: 3}, {spot_id: 9, spot_no: 9, gate_id: 3}, {spot_id: 3, spot_no: 3, gate_id: 3}, {spot_id: 8, spot_no: 8, gate_id: 2}, {spot_id: 13, spot_no: 14, gate_id: 2}, {spot_id: 2, spot_no: 2, gate_id: 2}, {spot_id: 7, spot_no: 7, gate_id: 1}, {spot_id: 12, spot_no: 13, gate_id: 1}]; gate_id_counter={} maximum=0 arr.map(ele => { // Create a frequency map of each value and their count { '1': 2, '2': 3, '3': 3, '4': 3, '5': 3, '6': 1 } // Choosing the maximum from the frequency map if( ele.gate_id in gate_id_counter){ gate_id_counter[ele.gate_id]+=1 if( gate_id_counter[ele.gate_id]>= maximum){ maximum=gate_id_counter[ele.gate_id] } } else{ gate_id_counter[ele.gate_id]=1 } }) console.log("Maximum count is "+ maximum)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM