Ad
Remove Duplicated Objects In JavaScript Array Not Working
First of, I am aware that there are LOTS of answers on SO on this, but I am having some issues with them, that is why I post another question on this topic.
So here is my Array of Objects:
0: {id: 'lAYOUT', label: 'lAYOUT', items: 'val1'}
1: {id: 'tecst', label: 'tecst', items: 'val1'}
2: {id: 'tecst', label: 'tecst', items: 'val1'}
I am trying to filter out that there would be only 2 values, since there are 2 objects in array that are the same. I would like to make unique objects by items
and label
.
This is how I am trying to do it with lodash
:
const filteredArray = uniq(nestedItems, (item, key, a) => item.items && item.label)
But it keeps returning me all 3 elements still.
I also tried it like this:
const filteredArray = [...new Set(nestedItems)]
Ad
Answer
Using Filter get the particular object value, index and array
.
Using FindIndex get the particular array object. and compare filter object
and findindex object
, if it return false then push in new array! and make new unique array !
Try this code !
let arr = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' },
{ id: 'tecst', label: 'tecst', items: 'val1' },
{ id: 'tecst', label: 'tecst', items: 'val1' }];
let newArr = arr.filter((value, index, self) =>
index === self.findIndex((t) => (
t.label === value.label && t.items === value.items
))
);
console.log(newArr, 'newArr');
Ad
source: stackoverflow.com
Related Questions
- → 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