Remove duplicated objects in JavaScript Array not working
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');
You can use hash grouping to filter by several keys:
const data = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }];
const unique = Object.values(data.reduce((acc, obj) => {
const hash = `${obj.id}-${obj.label}`;
acc[hash] = obj;
return acc;
}, {}));
console.log(unique);
.as-console-wrapper{min-height: 100%!important; top: 0}
Same result with lodash
const data = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }];
const result = _.uniqWith(data, (o1, o2) => `${o1.id}-${o1.label}` === `${o2.id}-${o2.label}`);
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js" integrity="sha512-2iwCHjuj+PmdCyvb88rMOch0UcKQxVHi/gsAml1fN3eg82IDaO/cdzzeXX4iF2VzIIes7pODE1/G0ts3QBwslA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>