Hacker News new | past | comments | ask | show | jobs | submit login

> Is there any use case where you would want to deal with sparse arrays?

Not really. Now explain why [,,,].map((e,i) => i) is [,,,] instead of [1,2,3] please ;)




(assuming you're really asking) It's because JS has a notion of array elements being "empty", and the map operation skips empty elements. Basically "empty" means the element has never had a value assigned to it, but its index is less than the array's length property.

    Array(4)               // [empty × 4]
    a=[]; a.length=4; a    // [empty × 4]
    Array(4).map(n => n)   // [empty × 4]
    [,,1,,].map(n => n)    // [empty × 2, 1, empty]
My go-to way of avoiding this annoyance is "Array.from(Array(N))":

    Array.from(Array(4)).map((n,i) => i)  // [0, 1, 2, 3]
Alternately there's a recent "fill" method, that assigns all elements (including empty ones) to a given value:

    Array(4).fill(1)      // [1, 1, 1, 1]




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: