-1

I want to edit the label text so that whenever there are duplicates of the same label name, they are incremented so that they could be differentiated when displayed.

So the input data looks below:

const brandName = [
  {
    id: '1',
    label: 'Nike'
  },
  {
    id: '2',
    label: 'Adidas'
  },
  {
    id: '3'
    label: 'Nike'
  }
]

And the output data of the function should display this:

const newBrandName = [
  {
    id: '1',
    label: 'Nike (1)'
  },
  {
    id: '2',
    label: 'Adidas'
  },
  {
    id: '3'
    label: 'Nike (2)'
  }
]

Here is my attempt:

function findDuplicates(brandName){
  var l = 0
  var r = tournaments.length - 1
  var count = 1
  while(r < tournaments.length){
    if(tournaments[l].label === tournaments[r].label){
      tournaments[l].label += count
      count += 1
      tournaments[r].label += count
    }
    r -= 1
  }
}

Is there a way I could use a JavaScript inbuilt array function?

Panface
  • 81
  • 6

1 Answers1

0

Not sure how your attempt comes up with tournaments, but here is my attempt;


First, we group the brands by label, then we know which one are found multiple times.

Then using reduce() we can flatten the multidimensional back to the array you started with, but add the (index + 1) for those where the array has more then 1 object in it

Note: The order of object in the array won't be the after this!

const brandName = [
  {
    id: '1',
    label: 'Nike'
  },
  {
    id: '2',
    label: 'Adidas'
  },
  {
    id: '3',
    label: 'Nike'
  }
];

const grouped = brandName.reduce((c, p) => {
    (c[p.label] ||= []).push(p);
    return c;
}, {});

const wrapped = Object.values(grouped).reduce((c, i) => {
  if (i.length > 1) {
      i = i.map((a, i) => {
          a.label = `${a.label} (${i + 1})`;
          return a;
      })
  }
  return [ ...c, ...i ];
}, []);

console.log(wrapped);

The above logs:

[
  {
    "id": "1",
    "label": "Nike (1)"
  },
  {
    "id": "3",
    "label": "Nike (2)"
  },
  {
    "id": "2",
    "label": "Adidas"
  }
]
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Brilliant solution @0stone0, it works flawlessly. Although I'm getting an error message from TypeScript saying "Object is of type 'unknown'.ts(2571)" and "Type 'unknown' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488). " Do you have any quick solution to that? – Panface Aug 31 '22 at 15:46