Skip to content

Instantly share code, notes, and snippets.

@KKrisu
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KKrisu/6fa4d17c31fb636f9eee to your computer and use it in GitHub Desktop.
Save KKrisu/6fa4d17c31fb636f9eee to your computer and use it in GitHub Desktop.
JS Sparse Arrays

input: var a = [2, 3, 5]
Task: we want to fill array with undefineds to 6th element.
output: [2, 3, 5, undefined, undefined, undefined]

ES5 solutions:

  1. a.length = 6 result: [2, 3, 5, undefined x 3]
    Problem: this array has sparse elements (holes) on elements 3-5. We can iterate through it like: for (i = a.length ; i-- ;) {}, but when we iterate like: a.forEach(callback) it only goes through iterable values.

  2. Classic for loop:
    for (i = a.length; i < 6; i++) {a.push(undefined)}

ES6 solutions:

  1. ES6 array.prototype.fill(value, startIndex?, endIndex?)

    a.length = 6;
    a.fill(undefined, 3, 6);
    
  2. ES6 Array.from the winner !!

    a.length = 6;
    a = Array.from(array);
    

    Array.from is great function. Useful to convert arguments to real array or to fill holes in sparse arrays: Array.from([2, undefined x 2, 3, undefined x 3]) gives [2, undefined, undefined, 3, undefined, undefined, undefined]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment