2

Which is the best way to set an array of n dimensions from a function?

var v1 = [1,2,3];
var v2 = [[1,2],[3,4]];

// only valid for 1-dimension
function set(arr, dim, v) {
    arr[dim] = v;
}

set(v1, 2, 33);
4
  • 1
    You want to assign ALL elements the same value? If it is n-dimensional, you need n indices to set a particular element. Commented Oct 24, 2012 at 22:24
  • But there are multiple elements at that dimension, you need to specify which index to modify. That is with one dimension, you just need an index, with two dimensions, you need two indexes and so on Commented Oct 24, 2012 at 22:26
  • So as I said, you need n indices. For a 2d array like the example, you need 2 indices. Commented Oct 24, 2012 at 22:27
  • yes, they could be passed into an array: set(v2, [0,2], 22), but how are passed from the parameter? Commented Oct 24, 2012 at 22:29

1 Answer 1

3

Your function can't work as designed it needs an index for each dimension

You'd need something like the following http://jsfiddle.net/nZmJT/1/

function setValueInArray(arr, value, index /*, index, index, ... */ ) {
    var arrToSet = arr;
    for (var i = 2; i < arguments.length - 1; i++) {
       arrToSet = arr[arguments[i]];
    }
    arrToSet[arguments[i]]= value;
    return arr;
}


var v1 = [1,2,3];
var v2 = [[1,2],[3,4]];

console.log( setValueInArray(v1, 0, 0) ); // [0,2,3]
console.log( setValueInArray(v2, 0, 0, 0) ); //[[0,2],[3,4]]

Please share with us why you'd like this. I can't think of code that can be generalized to work with multiple dimensions, you usually know the dimension, and just set it like...

v1[2][3] = 'anything';

Since in your case, you wouldn't know how many indexes to pass (otherwise you'd just use bracket access), the following may be a better fit

function setValueInArray(arr, value, indexes) {
    var arrToSet = arr;
    for (var i = 0; i < indexes.length - 1; i++) {
       arrToSet = arr[indexes[i]];
    }
    arrToSet[indexes[i]] = value;
    return arr;
}

Then you can call it passing the array of indexes which is created by some code outside of your control.

setValueInArray(v1, 0, indexes);
Sign up to request clarification or add additional context in comments.

4 Comments

+1, although I'd add an array-generator in the "unknown indizes" case for non-existing indizes.
It's part of a complex function, but one of its functionalities is to initialize an array of n-dimensions with an initial value. Thanks!
@Bergi Yes, you are right. But I'm not worried about edge cases, just guiding the OP on what needs to happen to achieve what they need, the less noise, the better, IMHO.
@Marc: If you already have a function to initialize n-dimensional objects, you should be familiar with the used code mechanism and be able to integrate it easily.

Your Answer

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