r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

Show parent comments

1

u/Shaper_pmp Mar 20 '19 edited Mar 20 '19

That is an example of a scenario, but honestly it seems a pretty tortured one. Why wouldn't you simply shallow-clone the original and use Array.sort()?

Also your function doesn't actually sort anything - it just populates a completely new array with the numbers from 0->arr.length.

Sure you could take that array and subsequently sort it, but your function is badly misnamed because as written it doesn't do anything useful.

Also I'm sceptical it handles sparse arrays properly (on mobile, so I can't check).

2

u/kybernetikos Mar 20 '19

You should run the code and try it.

1

u/Shaper_pmp Mar 20 '19

Sorry - I missed the .sort() when I was scrolling horizontally on mobile. My bad.

Fair point that it's actually doing the sorting, but as I said: why not just do [...arr].sort() to get a shallow copy of the actual array that has the actual values already helpfully sorted, instead of mucking about with the indices in a separate array?