let obj = [
{ id : 1 },
{ id : 10 },
{ brand : 12 },
{ id : 15 },
{ id : 18 },
{ image_link : 'some link' },
{ price : 10 },
{ brand : 111 },
{ image_link : 'some link 2' }
];
I have this array of object. I want filter this object so that I can get an object without duplicate keys.
I am trying this:
let uniqueIds = [];
let unique = obj.filter( (element ) => {
let key = Object.keys(element)[0];
let isDuplicate = uniqueIds.includes(element.key);
if (!isDuplicate) {
uniqueIds.push(element.key);
return true;
}
return false;
});
console.log( unique )
But everytime it’s showing me :
[ { id: 1 } ]
My expected output:
[
{ id : 18 },
{ price : 10 },
{ brand : 111 },
{ image_link : 'some link 2' }
];
>Solution :
You can filter your array based on whether the object’s key is the last occurrence of that key (checked using lastIndexOf) in the array:
let obj = [
{ id : 1 },
{ id : 10 },
{ brand : 12 },
{ id : 15 },
{ id : 18 },
{ image_link : 'some link' },
{ price : 10 },
{ brand : 111 },
{ image_link : 'some link 2' }
];
const keys = obj.map(o => Object.keys(o)[0])
const result = obj.filter((o, i) => keys.lastIndexOf(Object.keys(o)[0]) == i)
console.log(result)