3 回答
![?](http://img1.sycdn.imooc.com/5333a1bc00014e8302000200-100-100.jpg)
TA贡献1876条经验 获得超7个赞
您可以通过对同一个组数组使用带有哈希表的临时对象来使用map 排序。从中取出所用数组的长度作为排序组。
排序与组和值一起发生。
结果与排序的临时数组的索引映射。
var array = [1,2,2,3,1,4,4,2,9,8],
groups = Object.create(null),
result = array
.map((value, index) => ({ index, value, group: groups[value] = (groups[value] || 0 ) + 1 }))
.sort((a, b) => a.group - b.group || a.value - b.value)
.map(({ value }) => value);
console.log(...result);
![?](http://img1.sycdn.imooc.com/545868190001d52602200220-100-100.jpg)
TA贡献1890条经验 获得超9个赞
您可以创建一个group对象,该对象将每个数字创建为键,并将该数字的数组创建为值。然后,遍历对象并将每个数字添加到输出。每次数组变空时,删除键。运行这个直到对象没有剩下的键。
const input = [1, 2, 2, 3, 1, 4, 4, 2, 9, 8],
group = {},
output = [];
input.forEach(n => (group[n] = group[n] || []).push(n))
while (Object.keys(group).length > 0) {
for (const key in group) {
output.push(group[key].pop())
if (group[key].length === 0)
delete group[key];
}
}
console.log(output)
![?](http://img1.sycdn.imooc.com/533e4c1500010baf02200220-100-100.jpg)
TA贡献2065条经验 获得超14个赞
以下是您可以采取的方法 - 评论详细说明了每个步骤的用途:
const a = [1, 2, 2, 3, 1, 4, 4, 2, 9, 8];
//Create an occurrence map
const map = a.reduce((accum, i) => {
if (accum[i]) {
accum[i] += 1;
} else {
accum[i] = 1;
}
return accum;
}, {});
//We need to iterate the map as many times as the largest value
const iterations = Math.max(...Object.values(map));
const sorted = [];
for (let i = 0; i < iterations; i += 1) {
Object.entries(map).forEach(entry => {
const [val, count] = entry;
if (count > 0) {
sorted.push(parseInt(val)); //Add it to our sorted array
map[val] -= 1; //Reduce the number of occurrences in the map for this key
}
});
}
console.log(sorted);
添加回答
举报