Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates from an object array using spread operator

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.

like image 201
tracer Avatar asked Aug 08 '18 08:08

tracer


People also ask

Does spread operator remove duplicates?

Use the spread operator to remove duplicates items and to sort a array of numbers and objects, without destruct the original array.

How do you remove duplicates from an array of objects?

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.

How do you remove duplicates from an array of arrays?

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.


1 Answers

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)
like image 93
Nenad Vracar Avatar answered Sep 19 '22 05:09

Nenad Vracar