Search code examples
javascriptarrayssparse-array

Create sparse array in one line


Bash can create a sparse array in one line

names=([0]="Bob" [1]="Peter" [20]="$USER" [21]="Big Bad John")

§ Creating Arrays

Can JavaScript create a sparse array like this?


Solution

  • Technically, JavaScript has a sparse array literal, but it's cumbersome.

    var x = [8,,,,4,,,,6]
    

    I don't think you would want to use that as you wouldn't want to count the commas between [1] and [20]. Using objects instead of arrays seems more natural for JavaScript in this case.

    var names = {0: "Bob", 1: "Peter", 20: "$USER", 21: "Big Bad John"};
    

    Whether you quote the integers or not, you get the same result -- they're converted to strings to be used as keys in the object (which is basically a hash). (Oh, and I'm not doing anything with your shell variable here.) The same is true for access with []. If you look up names[0] it is actually the same as names['0'] in this case.

    However, if you want an actual array, a possible sparse-array-creation function is:

    function sparseArray() {
        var array = [];
        for (var i = 0; i < arguments.length; i += 2) {
            var index = arguments[i];
            var value = arguments[i + 1];
            array[index] = value;
        }
        return array;
    }
    var names = sparseArray(0, "Bob", 1, "Peter", 20, "$USER", 21, "Big Bad John");
    

    There's no error checking, so leaving off the final argument would set 21 -> undefined and giving a non-integer key will add it as an object property instead...