0

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 :)

1

2 Answers 2

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

As @Terminus pointed out it's even less code should you just reverse the condition of the while, loop from the end of the array down to 0...
1

On each comb.splice an element will be removed from the comb array and the comb.length will be decremented which will lead to the unexpected side effect of your loop to never reach some array indexes...

Quick fix:

comb.splice(i,1, []); // Remove the array at that index and replace it with an empty one

Proper fix: You should follow @Terminus' advice provided as comment

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.