为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

弑天下 2021-08-20 17:54:08
我有一个数组,其绝对值保证小于 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()或者编写一个单独的函数是否更容易和更正确?
查看完整描述

3 回答

?
幕布斯6054654

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);


查看完整回答
反对 回复 2021-08-20
?
当年话下

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)


查看完整回答
反对 回复 2021-08-20
?
翻翻过去那场雪

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);


查看完整回答
反对 回复 2021-08-20
  • 3 回答
  • 0 关注
  • 197 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信