Remove duplicate values from an array of objects in javascript
You can use array#reduce
and array#some
.
const arr = [
{label: 'All', value: 'All'},
{label: 'All', value: 'All'},
{label: 'Alex', value: 'Ninja'},
{label: 'Bill', value: 'Op'},
{label: 'Cill', value: 'iopop'}
]
var result = arr.reduce((unique, o) => {
if(!unique.some(obj => obj.label === o.label && obj.value === o.value)) {
unique.push(o);
}
return unique;
},[]);
console.log(result);
One liner solutions:
Unique by label
and value
arr.filter((v,i,a)=>a.findIndex(v2=>(v.label === v2.label && v.value===v2.value))===i)
Unique by all properties of the object:
arr.filter((v,i,a)=>a.findIndex(v2=>(JSON.stringify(v) === JSON.stringify(v2)))===i)
const things = {
thing: [
{ id: '12345', name: 'First name' },
{ id: '12345', name: 'Second name' },
{ id: '34536', name: 'Third name' },
],
};
const RemoveDuplicates = (array, key) => {
return array.reduce((arr, item) => {
const removed = arr.filter(i => i[key] !== item[key]);
return [...removed, item];
}, []);
};
console.log(RemoveDuplicates(things.thing, 'id'));
This code worked for me,
const addresses = [...]; // Some array I got from async call
const uniqueAddresses = Array.from(new Set(addresses.map(a => a.id)))
.map(id => {
return addresses.find(a => a.id === id)
})