亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何找到超過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 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號