4

i want to filter unique array of objects. my initial array would be

var initialObjArray=[ {lat:10,lon:20},{lat :10,lon:30} ,{lat :10,lon:20}];

my result array would be

var initialObjArray=[ {lat:10,lon:20},{lat :10,lon:30}];
Sadiqul
  • 145
  • 1
  • 11
  • Possible duplicate of [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – Nicola Oct 17 '19 at 15:31
  • 1
    i want to filter from array of object not only array – Sadiqul Oct 17 '19 at 15:35

2 Answers2

2

Try like this:

var result =  []
initialObjArray.forEach(item => {
  let count = result.filter(x => x.lat == item.lat && x.lon == item.lon).length

  if(count == 0) {
    result.push(item)
  }
})

Working Demo

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
1

You can use filter() and findIndex() to filter duplicate objects.

var initialObjArray = [{ lat:10, lon:20 }, { lat :10, lon:30 }, { lat :10, lon:20 }];

var unique = initialObjArray.filter((value, index, arr) => {
  return index === arr.findIndex(obj => obj.lat === value.lat && obj.lon === value.lon);
});

console.log(unique);
Nikhil
  • 6,493
  • 10
  • 31
  • 68