0

I'm trying to get a multidimensional array initialized to a value from a function. I've tried it but the result is not what I was expecting.

elemSize is an array with the dimensions, and init is the value for each element.

function MakeArray(elemSize, init) {
    var a = [];

    for (var i = 0; i < elemSize.length; i++) {
        var aj = [];
        for (var j = 0; j < elemSize[i]; j++) {
            aj[j] = init;
        }
        a[i] = aj;
    }

    return a;
}

This is the result

>>> var a = MakeArray([3,2], 5);
undefined
>>> a
[[5, 5, 5], [5, 5]]

but I would get:

[[5 5] [5 5] [5 5]]
1
  • Thanks to all by the different implementations to solve it. Commented Apr 18, 2012 at 23:23

3 Answers 3

1

You are a little wrong with your logic. Here is the code that outputs what you want (three arrays containing two elements ) :

function MakeArray(elemSize, init) {
    var a = [];

    for (var i = 0; i < elemSize[0]; i++) {
        var aj = [];
        for (var j = 0; j < elemSize[1]; j++) {
            aj[j] = init;
        }
        a[i] = aj;
    }

    return a;
}

First element of elemSize represents the number of arrays, and the second one represents the length of each array.

Sign up to request clarification or add additional context in comments.

Comments

0

Don't iterate over elemSize.length and elemSize[i] but elemSize[0] and elemSize[1]:

function MakeArray(elemSize, init) {
    var a = [];

    for (var i = 0; i < elemSize[0]; i++) {
        var aj = [];
        for (var j = 0; j < elemSize[1]; j++) {
            aj[j] = init;
        }
        a[i] = aj;
    }

    return a;
}

If you want a real multidimensional array, then you have to create a recursive function as your looping approach doesn't work for this:

function MakeArray(elemSize,init){
    if(elemSize.length === 0)
        return init;

    var result = [];
    var otherSize = elemSize.slice(1);
    var otherArray = MakeArray(otherSize,init); 
    for(var i = 0; i < elemSize[0]; ++i){
        result.push(otherArray);
    }
    return result;
}

var myArray = MakeArray([5,5,5],2);

Comments

0

You need a recursive algorithm to create arrays with arbitrary amount of dimensions.

function MakeArray(sizes, init) {
    var a = [];
    if (sizes.length > 1) {
        var b = sizes.slice(1);
        for (var i = 0; i < sizes[0]; i++) {
            a.push( MakeArray(b, init) );
        }
    } else {
        for (var i = 0; i < sizes[0]; i++) {
            a.push( init );
        }
    }
    return a;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.