Ad

Search Array Without Duplicates React.js

I have an array with objects smth like this:

arr = [
    {name: 'Igor', ....},
    {name: 'Anton', .... },
    {name: 'Igor', .... },
    {name: 'Peter', .... },
    {name: 'Igor', .... }
]

I need to get all the names from atrray, without duplicates. I tried looking like this

var names = [];
arr.forEach((item) => {
  if (!names.some(val => val === item)) {
    names.push(item.name);
  }
}

But I get all the names including duplicates

upd: I am using React If I push just names.push(item.name); to array everything works, I get array [Igor, Anton, Peter]. But! If I push items like this:

chat.forEach((item) => {
  if (names.indexOf(item.name) === -1) 
    names.push(<UserItem name={item.name} />);
});

I get array with 5 li elements: Igor, Anton, Igor, Peter, Igor. This is not duplicate quiestion!

Ad

Answer

Close, you just have to check the array for dupes

var names = [];

arr.forEach(function(obj) {
    if (names.indexOf(obj.name) === -1) names.push(obj.name);
});

var template = names.map(function(name) {
    return <UserItem name={name} />;
});

or

arr.forEach( v => names.indexOf(v.name) === -1 ? names.push(v.name) : null);
Ad
source: stackoverflow.com
Ad