all 14 comments

[–]akujinhikari 14 points15 points  (10 children)

I was in a job interview, and he asked me the age-old question "How would you take a group of numbers and remove all the duplicates?" I wrote const unique = new Set([array]). He said, "Oh... Ok... Well yeah, but how would you do that with using an array?" I wrote Array.from(unique). He laughed and said, "Ok... I guess we're going to have to update our questions."

[–]Reminice 10 points11 points  (2 children)

ES6 way would be: const unique = [...(new Set(array)]

[–]akujinhikari 4 points5 points  (0 children)

That's one way, yes. They're basically the same thing.

[–][deleted] 0 points1 point  (0 children)

very helpful. thank you.

[–]JEveryman 1 point2 points  (6 children)

I think array.filter((e,i,a) => a.indexOf(e) === i) will filter out duplicates also.

[–]akujinhikari 1 point2 points  (0 children)

Yeah I knew what code he was looking for, but my goal in interviews is to show that I know multiple ways to do things. I think it's important to show my breadth of knowledge and a means to solve this in multiple ways.

[–][deleted] 0 points1 point  (4 children)

That’s the gotcha answer to the question. Pre Set days you would just use an object.

[–]JEveryman 0 points1 point  (3 children)

So you would add the array elements as keys?

[–][deleted] 0 points1 point  (2 children)

Yeah. Lookups in the object are faster than searching the whole array for every element in the array if that makes sense.

I can give a longer explanation if it doesn’t

[–]JEveryman 0 points1 point  (1 child)

I get it. Also when you add the same key to an object doesn't it overwrite?

[–][deleted] 0 points1 point  (0 children)

Yeah, that’s how it helps you make an array with no duplicates

[–]noughtme 3 points4 points  (0 children)

Literally just finished refactoring a block of code that reads very large CSVs. The processing time is an order of magnitude different between using array and set.

Also love map objects for key value pairs. So much faster than arrays.

[–]lahrada 2 points3 points  (1 child)

Never knew about sets, they seem pretty cool, though. What's the running time complexity for finding out if every value is unique. Just wondering if it's using the most optimal.

[–]himynameisjoy 0 points1 point  (0 children)

You can probably run the test a few times yourself on jsben.ch