猿问

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

让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,4

2在 arr 中也是重复的。这样, arr中的所有2都转换为升序2,3

请提供一个演示。非常感谢您的细读。


沧海一幻觉
浏览 108回答 3
3回答

拉莫斯之舞

您可以采用单循环方法,为下一个映射提供替换值。这种方法只接受数字,但如果需要,您可以将所有值转换为数字对于任何重复的数字,它从对象中获取增加的值。1, 5, 2, 1, 4, 1, 9, 1, 21        2     3     4      2                 3const    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);

DIEA

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

开心每一天1111

使用Array.prototype.reduce,您可以获得数组的重复索引信息input。它将被获取为这种格式。{&nbsp; 1: [0, 3, 5, 7],&nbsp; 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) => {&nbsp; acc[curV] ? acc[curV].push(curI) : acc[curV] = [curI];&nbsp; return acc;}, {});let output = [ ...input ];Object.entries(duplicates).forEach(([ key, value ]) => {&nbsp; if (value.length > 1) {&nbsp; &nbsp; for (let index = 1; index < value.length; index ++) {&nbsp; &nbsp; &nbsp; output.splice(value[index], 1, (parseInt(key) + index).toString());&nbsp; &nbsp; }&nbsp; }});console.log(output);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答