0

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!

Igor Kim
  • 77
  • 1
  • 10

2 Answers2

3

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);
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

You can use names.indexOf which returns -1 if it is not found, so you can add it then.

arr.forEach(function(item) {
    if (names.indexOf(item) === -1) {
      names.push(item);
    }
});
MannfromReno
  • 1,276
  • 1
  • 14
  • 32