Search code examples
javascriptarraysmultidimensional-arraysplice

How can i remove an array from a multidimensional array in javascript?


So i currently have a multidimensional array with a ridiculous amount of arrays inside created by a function, in this structure

0: Array[10]
    0: Array[5]
    1: Array[5]
    2: Array[5]
    3: Array[5]
    4: Array[5]
    5: Array[5]
    6: Array[5]
    7: Array[5]
    8: 335.74
    9: 10341
1: Array[10]
2: Array[10]
3: Array[10]
.... and so on.

since the function that creates this array is a function that calculates all possible combinations of the 8 arrays that are within (the 2 last ones are appended afterwards) the array is VERY long so i would like to filter some of them out. Here im trying to remove all arrays which has a value above 10000 on the last element, if it does remove its whole array.

for (i = 0; i < comb.length; ++i) {
    if (comb[i][9] > 10000) {
        comb.splice([i],1);
    }
}

so in the first example the spot nr. 9 is above 10000, so it should splice/remove its parent. Currently this just removes parts of the array or nothing at all..

Any ideas? Thanks :)


Solution

  • In your code

    for (i = 0; i < comb.length; ++i) {
        if (comb[i][9] > 10000) {
            comb.splice([i],1);
        }
    }
    

    you delete an element and increase the counter by one. So for example you delete element 5 and you counter goes up to 6, the accessed element is now 7 and the 6th element is not processed.

              5         counter i
    0 1 2 3 4 5 6 7 8 9 array elements
              5         delete element
    0 1 2 3 4 6 7 8 9   array elements
                6       counter i
    0 1 2 3 4 6 7 8 9   array elements
    

    Therefore the for loop with fixed interval is not working here.

    Just go with while and increase only when it was not spliced.

    var i = comb.length;
    while (i--) {
        if (comb[i][9] > 10000) {
            comb.splice(i, 1);
        }
    }