1

I have a problem here that I can't deal with. There is little written about this on the internet. Well, when starting out, I need to make a function that will remove the duplicate data from the table, but the comparison of this data must be based on the data from the table object, below I will give an example because I do not know if I explained it well.

[
  { 
     id: 1234, 
     user: { 
       nickname: 'a' <-
     }
  },
  { 
     id: 1234, 
     user: { 
       nickname: 'b' <-
     }
  },
  { 
     id: 1234, 
     user: { 
       nickname: 'a' <-
     }
  },
]

Data is to be compared according to user.nickname.

I tried to do it this way

array.filter((value, index) => array.indexOf (value.user.nickname) === index)

but all I got was a blank array

[]

If anyone can help, I will be grateful because I have this situation.

olios
  • 69
  • 7
  • Does this answer your question? [How to remove all duplicates from an array of objects?](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) – Lioness100 Apr 24 '21 at 22:33

3 Answers3

1

Your approach is wrong. Here's one way you can do it instead:

  const mapOfNicknames = {};
  array.forEach((e)=> {
    const nick = e.user.nickname;

    // check if nick already exists in map
    if ( !mapOfNicknames[nick] ) {
      mapOfNicknames[nick] = e;
    }
  });

  // at this point, mapOfNicknames has a unique list
  const uniqueArray = Object.keys(mapOfNicknames).map( k => mapOfNicknames[k] );
Clinton Chau
  • 557
  • 2
  • 12
1

Using Array.filter as you try, should be a proper aproat:

const users = [
  {
    id: 1234,
    user: {
      nickname: "a",
    },
  },
  {
    id: 1234,
    user: {
      nickname: "b",
    },
  },
  {
    id: 1234,
    user: {
      nickname: "a",
    },
  },
];

let filteruniquebyUserName = users.filter(
  (user, index, users) => users.findIndex((compareUser) => compareUser.user.nickname === user.user.nickname) === index
);
console.log(filteruniquebyUserName);

See: How to remove all duplicates from an array of objects?

Another way a little more extended but easier to understand:

const data = [
  {
    id: 1234,
    user: {
      nickname: "a",
    },
  },
  {
    id: 1234,
    user: {
      nickname: "b",
    },
  },
  {
    id: 1234,
    user: {
      nickname: "b",
    },
  },
  {
    id: 1234,
    user: {
      nickname: "a",
    },
  },
];

let elementRepeated = [];

let filteruniquebyUserName = data.filter((user, index, data) => {
  if(elementRepeated.includes(user.user.nickname)) return;

  const numberOfRepeatUser = data.filter(element => element.user.nickname === user.user.nickname).length;
  if(numberOfRepeatUser > 1) elementRepeated.push(user.user.nickname);
  return user
});
console.log(filteruniquebyUserName);
0

Apparently you can't do an indexOf check in a nested object like you are doing it right now. See: Javascript indexOf on an array of objects

FireFighter
  • 686
  • 3
  • 6