-2

If there is the same id in the array, I want to delete it.
In the following, id3 and id4 are duplicated. I want to delete the duplicates and create an array like ①.
I used indexof as shown below, but I can't get rid of duplicate values ​​from the array.
If anyone knows, I would like to ask a professor

// users
     {id:1, name: 'aaaaa', type: "text"}
     {id:2, name: 'bbbbb', type: "text"}
     {id:3, name: 'ccccc', type: "text"}
     {id:3, name: 'dddddd', type: "text"}
     {id:4, name: 'eeeeee', type: "text"}
     {id:4, name: 'ffffff', type: "text"}
//①Array with duplicates removed
 {id:1, name: 'aaaaa', type: "text"}
 {id:2, name: 'bbbbb', type: "text"}
 {id:3, name: 'dddddd', type: "text"}
 {id:4, name: 'ffffff', type: "text"}
  const List = (users:Users[]) => {
    const arrayUsers = users.filter((x, i, self) => {
      return self.indexOf(x) === i;
    });
sato desu
  • 59
  • 2
  • 7

1 Answers1

2

You could use Array.prototype.reduce() method to remove the duplicates. Traverse the array and group it by id.

const users = [
  { id: 1, name: 'aaaaa', type: 'text' },
  { id: 2, name: 'bbbbb', type: 'text' },
  { id: 3, name: 'ccccc', type: 'text' },
  { id: 3, name: 'dddddd', type: 'text' },
  { id: 4, name: 'eeeeee', type: 'text' },
  { id: 4, name: 'ffffff', type: 'text' },
];

const ret = Object.values(
  users.reduce((prev, c) => {
    const p = prev;
    const key = c.id;
    p[key] = c;
    return p;
  }, {})
);
console.log(ret);
mr hr
  • 3,162
  • 2
  • 9
  • 19