Skip to content Skip to sidebar Skip to footer

Js Multidimensional Array Modify Value

I am in a function where i fetch a multidimensional array from the parent container. The array fetched doesn't always have the same dimensions (it can be 1D, 2D, 3D, 4D, ...). I ha

Solution 1:

I have found a solution :

function(coordinates_array, value) {
    var multi_dim_array = getArrayByName(another_param);
    //Transform [1, 2, 3] in "[1][2][3]"var coord = JSON.stringify(coordinates_array).replace(/,/g, '][');

    eval('multi_dim_array' + coord + ' = ' + value);
}

But i'm not quite satisfied with it. Can anyone find a better solution ?

Or can anyone tell me if my approach is good performance wise. I'll call this method very often : more than 700 multidimentional arrays in total, and they can all be uptated very often (like when i resize a div, i need to update 4 different arrays (top, left, width, height), ...).


After several perf tests, I decided to go for an 'ugly' switch case :

function(coordinates_array, value) {
    var multi_dim_array = getArrayByName(another_param);

    switch(coordinates_array.length) {
        case1: multi_dim_array[coordinates_array[0]] = value;break;
        case2: multi_dim_array[coordinates_array[0]][coordinates_array[1]] = value;break;
        case3: multi_dim_array[coordinates_array[0]][coordinates_array[1]][coordinates_array[2]] = value;break;
        case.....
    }
}

Indeed, for a simple calling test over 100 000 iterations, the switch case solution revealed to be over 500x faster than the eval() one (10ms to complete the switch case vs over 5000ms to complete the eval test).

If anyone finds a cleaner solution than the switch case one, i'm still interested, even if it's a little bit less performant (not more than ~2x ; 3x times though).

Post a Comment for "Js Multidimensional Array Modify Value"