Suhail Mumtaz Awan
Suhail Mumtaz Awan

Reputation: 3483

Removing duplicate arrays of an array : javascript

I am working with javascript arrays, where i have an array of arrays like,

var arr = [ 
  [ 73.0191641, 33.5720131 ],
  [ 73.0191641, 33.5720131 ],  
  [ 3.0191641, 33.5720131 ],
  [ 73.0191641, 33.5720131 ],
  [ 73.0191641, 33.5720131 ],
  [ 73.0192222, 33.5778921 ],
  [ 73.0192222, 33.5778921 ]];

There, i needed to remove the duplicate arrays. I have tried this method but it didn't worked for me, may be i am missing or doing something wrong.

var distinctArr = Array.from(new Set(arr));

Although this method works only for array of objects. If someone can help, please do help. Thanks for your time.

Upvotes: 1

Views: 1485

Answers (2)

kind user
kind user

Reputation: 41913

You can use following approach.

var arr = [ { person: { amount: [1,1] } }, { person: { amount: [1,1] } }, { person: { amount: [2,1] } }, { person: { amount: [1,2] } }, { person: { amount: [1,2] } }];

   hash = [...new Set(arr.map(v => JSON.stringify(v)))].map(v => JSON.parse(v));
   
   document.write(`<pre>${JSON.stringify(hash, null, 2)}</pre>`);

Upvotes: 1

dasiekjs
dasiekjs

Reputation: 76

Lodash is great lib for doing this little things.

uniqWith with compare isEqual should resolve your problem.

var arr = [ 
  [ 73.0191641, 33.5720131 ],
  [ 73.0191641, 33.5720131 ],  
  [ 3.0191641, 33.5720131 ],
  [ 73.0191641, 33.5720131 ],
  [ 73.0191641, 33.5720131 ],
  [ 73.0192222, 33.5778921 ],
  [ 73.0192222, 33.5778921 ]];

_.uniqWith(arr,_.isEqual)

return -> [Array(2), Array(2), Array(2)]

Upvotes: 3

Related Questions