2020-09-27

Create unique values from duplicates in Javascript array of objects

I have an array of duplicated objects in Javascript. I want to create an array of unique objects by adding the index of occurrence of the individual value.

This is my initial data:

const array= [
  {name:"A"},
  {name:"A"},
  {name:"A"},
  {name:"B"},
  {name:"B"},
  {name:"C"},
  {name:"C"},
];

This is expected end result:

const array= [
  {name:"A-0"},
  {name:"A-1"},
  {name:"A-2"},
  {name:"B-0"},
  {name:"B-1"},
  {name:"C-0"},
  {name:"C-1"},
];

I feel like this should be fairly simple, but got stuck on it for a while. Can you please advise how I'd go about this? Also if possible, I need it efficient as the array can hold up to 1000 items.


EDIT: This is my solution, but I don't feel like it's very efficient.

const array = [
  { name: "A" },
  { name: "A" },
  { name: "C" },
  { name: "B" },
  { name: "A" },
  { name: "C" },
  { name: "B" },
];

const sortedArray = _.sortBy(array, 'name');

let previousItem = {
   name: '',
   counter: 0
};
const indexedArray = sortedArray.map((item) => {
  if (item.name === previousItem.name) {
    previousItem.counter += 1;
    const name = `${item.name}-${previousItem.counter}`;
    return { name };
  } else {
    previousItem = { name: item.name, counter: 0};
    return item;
  }
});


from Recent Questions - Stack Overflow https://ift.tt/2G33XTF
https://ift.tt/eA8V8J

No comments:

Post a Comment