如何在 JavaScript 中对数字数组进行排序,确保在添加重复项之前完成第一个计数?



我正在使用的这个数字数组目前看起来是这样的;

count = [1,4,3,1,2,3,4,5,6,2,3,5,7];

我怎样才能转换和排序它以使其看起来像这样;

count = [1,2,3,4,5,6,7,1,2,3,3,4,5];

请帮忙,关于如何处理这个问题的任何想法?

1(获取唯一元素并进行排序
2(获取剩余元素并进行排序
3( 组合 (1( 和 (2( 数组。

count = [1, 4, 3, 1, 2, 3, 4, 5, 6, 2, 3, 5, 7];
const spSort = arr => {
const uniq = [...new Set([...arr])];
const rem = [];
const temp_set = new Set([...arr]);
arr.forEach(x => {
if (temp_set.has(x)) {
temp_set.delete(x);
} else {
rem.push(x);
}
});
return [...uniq.sort(), ...rem.sort()];
};
console.log(spSort(count));

使用Set创建唯一编号,并使用哈希对象保留重复项计数:

const count = [1, 4, 3, 1, 2, 3, 4, 5, 6, 2, 3, 5, 7];
const hash = count.reduce((obj, num) => {
obj[num] = obj[num] ? ++obj[num] : 1;
return obj;
}, {});
const uniq = [...new Set(count)].sort();
uniq.forEach((num, _, arr) => {
while (--hash[num]) arr.push(num);
});
console.info(uniq);

相关内容

最新更新