News for hackers. Stuff that matters.
Re:Ask HN: What is the most beautiful piece of code you've e... by _bxg1 on Monday October 28, 2019 @12:35AM (#21374310)
I like this bit of JavaScript for uniquifying an array:

  array.filter((item, index, arr) => arr.indexOf(item) === index)
It works because indexOf returns the index of the first occurrence of the item, so you're asking whether this occurrence is the first occurrence.
Re:Ask HN: What is the most beautiful piece of code you've e... by superfrank on Monday October 28, 2019 @12:44AM (#21374342)
Personally I like this one, although it only works for an array of primitive types.

    const unique = [...new Set(arr)];
Re:Ask HN: What is the most beautiful piece of code you've e... by _bxg1 on Monday October 28, 2019 @12:45AM (#21374354)
The other advantage of the filter one is it can be stuck in the middle of a bunch of other list operations - map(), sort(), slice(), other filters(). Also, you can use findIndex() instead of indexOf() to match any arbitrary predicate, instead of exact equivalence.
Re:Ask HN: What is the most beautiful piece of code you've e... by superfrank on Monday October 28, 2019 @12:49AM (#21374369)
Oh, for sure. I know .filter() has it's place, so if you need anything beyond making the array unique, I'd definitely use your solution.

The one I posted just blew my mind a little the first time I saw it, so I love to share it. I guess I never really considered spreading a set.

Re:Ask HN: What is the most beautiful piece of code you've e... by SzamarCsacsi on Monday October 28, 2019 @06:26AM (#21375702)
I like this neat little code to filter out falsy values:

  array.filter(Boolean)
Re:Ask HN: What is the most beautiful piece of code you've e... by throwaway_n on Monday October 28, 2019 @12:39AM (#21374324)
This is O(n^2) though
Re:Ask HN: What is the most beautiful piece of code you've e... by _bxg1 on Monday October 28, 2019 @12:41AM (#21374331)
All of JS's list processing functions are pretty inefficient, since at the bare minimum each one creates and copies to a new array (as opposed to, say, Rust iterators). You use them when elegance is more important than performance; N^2 is fine when N is eight.
Re:Ask HN: What is the most beautiful piece of code you've e... by kadoban on Monday October 28, 2019 @05:14AM (#21375389)
That's always such a dangerous proposition though. Sure _you_ remember it's only fine when N is 8, but then the next guy comes along, or the input constraints change, or future you forgets because it _is_ fairly elegant looking.

I try not to leave grenades laying around too often, myself.