I have array of objects like this,
let data = [
{ id: 1, name: 'a' },
{ id: 1, name: 'b'},
{ id: 1, name: 'a'},
{ id: 2, name: 'a'},
{ id: 2, name: 'b'},
{ id: 3, name: 'c'},
{ id: 3, name: 'c'}
]
I am trying to achieve unique combination of id and name, so expected output should be like,
output
[
{ id: 1, name: 'a'},
{ id: 1, name: 'b'},
{ id: 2, name: 'a'},
{ id: 2, name: 'b'},
{ id: 3, name: 'c'}
]
I have tried Set method but could not do it for key, value pair.
Please could someone help.
Thanks
Edit- 1
Most solutions have array of string, number or object with one key-value pair. I have two key-value pairs in object.
>Solution :
You can actually use Set for it, you just have to use combination of values that identifies if it is unique.
let data = [
{ id: 1, name: 'a' },
{ id: 1, name: 'b'},
{ id: 1, name: 'a'},
{ id: 2, name: 'a'},
{ id: 2, name: 'b'},
{ id: 3, name: 'c'},
{ id: 3, name: 'c'}
]
const nodup = new Set();
data.forEach(item => nodup.add(`${item.id}-${item.name}`));
console.log(Array.from(nodup))
let uniqueData = Array.from(nodup).map(item => {
const data = item.split('-')
return {id: data[0], name: data[1]};
});
console.log(uniqueData);
After this script, if you want to have array with objects with id and name again, you can simply create it from the result.