JS:如何用新值替换数组中的重复元素

JS : How to replace duplicated elements in array with new values

我有一个数组,如下所示:

let arr = ['11','44','66','88','77','00','66','11','66']

可见,在这个数组中,有那些重复的元素:

我想遍历我的数组,以便找到重复的元素;并将它们从第二次出现替换为指示第一次出现索引

的字符串

我得到的数组是这样的:

let newarr = ['11','44','66','88','77','00','appears at 2','appears at 0','appears at 2']

你可以用这样的字符串替换重复项:

"出现在n" 其中 "n"是第一次出现的索引

试试这个:

const appearances = {}
const arr = ['11','44','66','88','77','00','66','11','66']

const newarr = arr.map((item, index) => {
  if (appearances[item] !== undefined) return `appears at ${appearances[item]}`
  else {
    appearances[item] = index
    return item
  }
})

console.log("new arr: ", newarr)

这是一个两步法:

  1. 创建一个记录第一次出现的对象

  2. 将源数组映射到具有替换的新数组

let arr = ['11', '44', '66', '88', '77', '00', '66', '11', '66'];

// record first occurences
const firsts = arr.reduce((acc, val, index) => {
  if (typeof acc[val] === 'undefined') {
    acc[val] = index;
  }
  return acc;
}, {});

console.log('firsts:', firsts);

// create array with substitutions
const newarr = arr.map((val, index) => {
  return (firsts[val] === index) ? val
    : `appears at ${firsts[val]}`
});

console.log(`newarr:`, newarr);

解决方案

let arr = ["11", "44", "66", "88", "77", "00", "66", "11", "66"].map(
  (value, index, self) => {
    if (self.indexOf(value, 0) !== index) {
      return `appears at ${self.indexOf(value, 0)}`;
    }
    return value;
  }
);
console.log(arr);

一个简短的方法,在索引的哈希 table 和条件运算符上闭包

const
    array = ['11', '44', '66', '88', '77', '00', '66', '11', '66'],
    result = array.map(
        (indices => (v, i) => (indices[v] ??= i) == i ? v : `seen at ${indices[v]}`)
        ({})
    );

console.log(result);