0

I have an array of objects with input like below

var jsonArray1 = [{id:'1',name:'John'},{id:'2',name:'Smith'},{id:'3',name:'Adam'},{id:'1',name:'John'}]

The id 1 appears twice and I would like to drop all duplicate records .i.e. my output should look like

[{id:'2',name:'Smith'},{id:'3',name:'Adam'}]

Can you please guide/direct me in how I can drop all duplicate records

  • There's no such thing as a JSON array. `jsonArray1` is an array of objects, nothing more. – Heretic Monkey Apr 26 '21 at 17:58
  • This is a similar question: [remove all elements that occur more than once from array](https://stackoverflow.com/questions/53066843) You need to implement the same for objects – adiga Apr 26 '21 at 18:28

1 Answers1

0

Create Map from an array where key of the Map is your desired id, duplicated won't be preserved (only last occurrence will). After just take the values from Map.

Removing all of occurrences of duplicates (this is what OP wanted):

const input = [{id:'1',name:'John'},
               {id:'2',name:'Smith'},
               {id:'3',name:'Adam'},
               {id:'1',name:'John'}]

const res = input.filter((x, i, arr) => 
                          arr.filter(e => e.id === x.id).length === 1)
console.log(res)

Preserving 1 occurrence of duplicates:

const input = [{id:'1',name:'John'},
               {id:'2',name:'Smith'},
               {id:'3',name:'Adam'},
               {id:'1',name:'John'}]

const unique = [...new Map(input.map(item => [item.id, item])).values()]
console.log(unique)
ulou
  • 5,542
  • 5
  • 37
  • 47
  • it drops just the duplicate record. my requirement is to drop all such occurrences where a duplicate is found. the output should be just [ { "id": "2", "name": "Smith" }, { "id": "3", "name": "Adam" } ] – Sadiq Sikkandhar Apr 26 '21 at 18:20
  • My bad, updated, check it now. – ulou Apr 26 '21 at 18:38