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

如何找到超过2个重复数字数组的索引并将索引处的项目转换为升序?

如何找到超过2个重复数字数组的索引并将索引处的项目转换为升序?

沧海一幻觉 2023-05-25 16:36:33
让arr = [' 1 ','5', '2' ,' 1 ','4',' 1 ','9',' 1 ', '2' ];output = [' 1 ','5', '2' ,' 2 ','4',' 3 ','9',' 4 ', '3' ];1在 arr 中是重复的。这样, arr中的所有1都转换为升序1,2,3,42在 arr 中也是重复的。这样, arr中的所有2都转换为升序2,3请提供一个演示。非常感谢您的细读。
查看完整描述

3 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

您可以采用单循环方法,为下一个映射提供替换值。这种方法只接受数字,但如果需要,您可以将所有值转换为数字


对于任何重复的数字,它从对象中获取增加的值。


1, 5, 2, 1, 4, 1, 9, 1, 2

1        2     3     4

      2                 3

const

    array = [1, 5, 2, 1, 4, 1, 9, 1, 2],

    values = {},

    result = array.map(v => v in values ? ++values[v] : (values[v] = v));


console.log(...result);


查看完整回答
反对 回复 2023-05-25
?
DIEA

TA贡献1820条经验 获得超2个赞

let arr = ["1", "5", "2", "1", "4", "1", "9", "1", "2"];

let flag = {};

let ret = arr.map((x) => {

  x = +x;

  if (!flag[x]) {

    flag[x] = x;

    return x;

  } else {

    flag[x] += 1;

    return flag[x];

  }

}).map(x => x + "");

console.log(ret);


查看完整回答
反对 回复 2023-05-25
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

使用Array.prototype.reduce,您可以获得数组的重复索引信息input。

它将被获取为这种格式。

{

  1: [0, 3, 5, 7],

  9: [2], ...

}


// Values are the duplicated index position.

根据该信息,您可以使用Array.splice如下函数替换该索引上具有 2 个以上重复项的数据。

const input = [ '1', '5', '2', '1', '4', '1', '9', '1', '2' ];


const duplicates = input.reduce((acc, curV, curI) => {

  acc[curV] ? acc[curV].push(curI) : acc[curV] = [curI];

  return acc;

}, {});


let output = [ ...input ];

Object.entries(duplicates).forEach(([ key, value ]) => {

  if (value.length > 1) {

    for (let index = 1; index < value.length; index ++) {

      output.splice(value[index], 1, (parseInt(key) + index).toString());

    }

  }

});


console.log(output);


查看完整回答
反对 回复 2023-05-25
  • 3 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

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