Search code examples
javascripttypescriptecmascript-6ecmascript-5

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


I ve an array which looks like this :

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

as visible , inside this array , there were those duplicated elements :

  • '11' in position 7
  • '66' in positions 6 and 8

I want to iterate over my array , so that , i find the duplicated elements ; and replace them from the second occurence with a string indicating the first occurrence index

my resulting array would like this :

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

as you can this the duplications are replaced with a string like this :

"appears at n" where "n" is the index of the first occurence


Solution

  • Try this:

    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)