search array without duplicates React.js
Ad
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
Ad
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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad