I have below object array with id as unique key":
var test = [
{id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},
{id: 2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""},
{id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},
{id: 3, PlaceRef: "*00011", Component: "ANR190", SubLocCode: "B1", BarCode: ""}
]
From this I want to retrieve unique objects using spread operator, I have tried using below code:
const uniKeys = [...(new Set(test.map(({ id }) => id)))];
I am able to retrieve id's only, how can I retrieve the unique objects using spread operator. Also, any new ES6 features implementation would be helpful.
Use the spread operator to remove duplicates items and to sort a array of numbers and objects, without destruct the original array.
To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.
To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
You could map
back to array of objects using find
method, this will return first object with that id.
var test = [{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},{id:2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""},{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},{id:3, PlaceRef: "*00011", Component: "ANR190", SubLocCode: "B1", BarCode: ""}]
var uniq = [...new Set(test.map(({id}) => id))].map(e => test.find(({id}) => id == e));
console.log(uniq)
You could also use filter
method instead.
var test = [{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},{id:2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""},{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},{id:3, PlaceRef: "*00011", Component: "ANR190", SubLocCode: "B1", BarCode: ""}]
var uniq = test.filter(function({id}) {
return !this[id] && (this[id] = id)
}, {})
console.log(uniq)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With