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!

0

2 Answers 2

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);
3
  • thanks that works but not in my case, can you help? I added info to question
    – Igor Kim
    Commented Dec 17, 2015 at 17:23
  • @IgorKim - just do it this way, then iterate over names with map() to create an array with the markup
    – adeneo
    Commented Dec 17, 2015 at 17:28
  • Thanks, that worked!
    – Igor Kim
    Commented Dec 17, 2015 at 17:38
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);
    }
});
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.