0

I have following object of zip codes. I am trying to get only the unique values of zip code so repeated values are removed.

this.listuser = [{"zip": 12345},{"zip": 78601},{ "zip": 12345},{ "zip": 78601}];

I am trying to remove duplicate values of zip and

this.resl=this.listuser.filter(zip, i,a)=> i===a.indedOf(zip));

Basically this does nothing. There is no error and still I see the duplicates. I have tried other solutions from Stack Overflow for some reason same thing no error but still duplicate show up.

Please let me know how to fix this so I can get unique values of zip code only.

J. Davidson
  • 3,297
  • 13
  • 54
  • 102
  • What is the purpose of your function inside `filter`? – Quan VO Feb 14 '19 at 16:50
  • @HereticMonkey the solution in that post is from 2010, I can get there to using loops and messy code. I want some modern solution to that. – J. Davidson Feb 14 '19 at 16:52
  • Then ask for the that in your question. The second answer uses ES2015 code, BTW. [This answer uses `Set` and does it in one line](https://stackoverflow.com/a/44601543/215552) and all of them answer your question. So, it is a duplicate. – Heretic Monkey Feb 14 '19 at 16:53
  • Thank you for the suggestion both worked the 2nd one and the one given here – J. Davidson Feb 14 '19 at 17:09

1 Answers1

1

your condition (zip, i,a)=> i===a.indexOf(zip) can't work because is expect to have the same object (means RAM memory address) to work, here you have different object with the same value on it.

To play around you have to use two loop to deduplicate your array like following :

var test = [{"zip": 12345},{"zip": 78601},{ "zip": 12345},{ "zip": 78601}];

var dedupe = test.reduce((accumulator, current) => {
  if (! accumulator.find(({zip}) => zip === current.zip)) {
    accumulator.push(current);
  }
  return accumulator;
}, []);

console.log(dedupe);
Yanis-git
  • 7,737
  • 3
  • 24
  • 41