Home > Back-end >  Find the duplicate in the object and add an increment value to it in javascript
Find the duplicate in the object and add an increment value to it in javascript

Time:09-01

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?

CodePudding user response:

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"
  }
]
  • Related