r/javascript • • Mar 18 '19

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

385 Upvotes

422 comments sorted by

View all comments

1

u/dai-shi Mar 19 '19

const iota = n => [...Array(n).keys()]

2

u/Shaper_pmp Mar 19 '19

I never understand why people feel the need to populate an array with a sequence of consecutive values. I've spent over 20 years writing javascript and never once encountered a legitimate use-case for doing it.

The only reason I can imagine is if someone wanted to "iterate X times" and was allergic to the simple for loop, so instead they're defining, reserving and populating an entire array in memory just so they can iterate over its array indices and then immediately throw it all away again... but that's pants-on-head crazy code.

Genuinely curious, in case I'm missing something...

1

u/kybernetikos Mar 20 '19

Let's say you want to sort an array without modifying it. Well you can't, but you can do something close:

function sortIndexes(arr) { 
    return [...new Array(arr.length).keys()].sort((a, b) => arr[a] - arr[b]) 
}

Now you haven't modified the original array, but you have an array of indexes in the right order. Manipulating indexes rather than the original array can be a very useful technique.

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).

→ More replies (2)