Skip to content Skip to sidebar Skip to footer

How Can I Rename Multiple Same Occurrences In Array

I want to rename my elements i have this array: Rename multiple same occurrences in array but i am getting a good result, i want this result: 'a', 'b', 'c' 'a1', 'f', 'r', 'b1', '

Solution 1:

I think you are almost there.. the tally[arr[i]]++ does not mean anything.. if you want to increase the number on the end, you have to have another object to tally the elements.. ex:

var arr = ['a', 'b', 'c', 'a', 'f', 'r', 'b', 'a'];
var tally = {};
for (var i = 0; i < arr.length; i++) {
  if(!tally[arr[i]]) {
    tally[arr[i]] = 1;
  }
  else {
    tally[arr[i]] = tally[arr[i]] + 1;
    arr[i] = arr[i] + (tally[arr[i]] - 1);
  }
  console.log(tally);
}
console.log('arr', arr)

Solution 2:

Use the tally to record counts for elements. Map the array and append counts larger than one...

const arr =  [{name:'a'},{name:'b'}, {name:'c'}, {name:'a'}, {name:'f'}, {name:'r'}, {name:'b'}, {name:'a'}];
let tally = {}
const result = arr.map(el => {
  const name = el.name;
  tally[name] = tally[name] ? tally[name]+1 : 1;
  return { name: tally[name] > 1 ? `${name}${tally[name]-1}` : name }
})

console.log(result)

Post a Comment for "How Can I Rename Multiple Same Occurrences In Array"