【发布时间】:2021-12-17 06:16:51
【问题描述】:
我想在数组中查找数字的出现,然后显示数字和出现的数字,这些数字按升序排序,如下所示:
let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];
// {'-10': 2, '-8': 1, '1': 2, '2': 3, '6': 2, '9': 3, '10': 1}
我通过将数组中的每个数字存储在一个对象中来找到它们的出现次数。当我尝试使用console.log numCount 时,除负数外,所有数字均按升序排序。
/*Find occurrences*/
let numCount = {};
for(let num of arr){
numCount[num] = numCount[num] ? numCount[num] + 1 : 1;
}
console.log(numCount);
//{ '1': 2, '2': 3, '6': 2, '9': 3, '10': 1, '-10': 2, '-8': 1 }
我查找了如何对对象进行排序,看起来这样做的方法是将它们存储在一个数组中,然后对其进行排序。所以这就是我尝试过的:
/*Store them in array and then sort it*/
let sortedArray = [];
for(let item in numCount){
sortedArray.push([item, numCount[item]]);
}
sortedArray.sort(function(a,b){
return a[0] - b[0];
});
/*
console.log(sortedArray);
[
[ '-10', 2 ],
[ '-8', 1 ],
[ '1', 2 ],
[ '2', 3 ],
[ '6', 2 ],
[ '9', 3 ],
[ '10', 1 ]
]
*/
下一个方法应该将它们显示在按升序排序的对象中,但是当我尝试它时,它在该对象的末尾以负数显示它们,就像在开始时一样。所以这是我卡住的部分。
let sortedObject = {};
sortedArray.forEach(function(item){
sortedObject[item[0]] = item[1];
})
/*console.log(sortedObject);
{ '1': 2, '2': 3, '6': 2, '9': 3, '10': 1, '-10': 2, '-8': 1 }
*/
完整代码:
let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];
/*Find occurrences*/
let numCount = {};
for(let num of arr){
numCount[num] = numCount[num] ? numCount[num] + 1 : 1;
}
/*Store them in array and then sort it*/
let sortedArray = [];
for(let item in numCount){
sortedArray.push([item, numCount[item]]);
}
sortedArray.sort(function(a,b){
return a[0] - b[0];
});
let sortedObject = {};
sortedArray.forEach(function(item){
sortedObject[item[0]] = item[1];
})
console.log(sortedObject);
【问题讨论】:
-
对象属性未排序。这是愚蠢的差事。
-
为什么你需要它成为一个对象,而不是(例如)你的 sortedArray?
-
@MikeM Does JavaScript guarantee object property order? 他们是。
-
我想这里的问题是键(或至少其中一些)被认为是整数,你不能改变顺序。
标签: javascript arrays sorting object