将数字数组拆分为已排序的组

我有一个数组,其绝对值保证小于 10。


我现在正在做的是使用Array.prototype.sort()以下方法按升序对其进行排序:


myArray.sort(function (a, b) {

    return a - b;

})

但任务是按组排序而不重复,换句话说,有一个数组


a = [1,2,2,3,1,4,4,2,9,8]


我需要得到输出


b = [1,2,3,4,8,9,1,2,4]


我有一个想法,使用Array.prototype.push()内部函数表达式将重复的数字添加到数组的末尾。但由于明显的原因,我不能这样做,因为存在范围:


myArray.sort(function (a, b) {

    if(a === b){

        this.myArray.push(b);

        return 0;

    }

    else{

        return a - b;

    }

})

是否可以使用我的想法来实现,Array.prototype.sort()或者编写一个单独的函数是否更容易和更正确?


弑天下
浏览 198回答 3
3回答

幕布斯6054654

您可以通过对同一个组数组使用带有哈希表的临时对象来使用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);

当年话下

您可以创建一个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)

翻翻过去那场雪

以下是您可以采取的方法 - 评论详细说明了每个步骤的用途:const a = [1, 2, 2, 3, 1, 4, 4, 2, 9, 8];//Create an occurrence mapconst map = a.reduce((accum, i) => {&nbsp; if (accum[i]) {&nbsp; &nbsp; accum[i] += 1;&nbsp; } else {&nbsp; &nbsp; accum[i] = 1;&nbsp; }&nbsp; return accum;}, {});//We need to iterate the map as many times as the largest valueconst iterations = Math.max(...Object.values(map));const sorted = [];for (let i = 0; i < iterations; i += 1) {&nbsp; Object.entries(map).forEach(entry => {&nbsp; &nbsp; const [val, count] = entry;&nbsp; &nbsp; if (count > 0) {&nbsp; &nbsp; &nbsp; sorted.push(parseInt(val)); //Add it to our sorted array&nbsp; &nbsp; &nbsp; map[val] -= 1; //Reduce the number of occurrences in the map for this key&nbsp; &nbsp; }&nbsp; });}console.log(sorted);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript