[SOLVED]Javascript used to remove specific ListElements (works but has one issue)
-
I am continuing my learning curve and today tried to create a button click on which removes all the ListElements from the ListModel that have property "quantity" ==0. Here is the JS code I put:
@ function removeZeroQuantity() {
var i = 0
for (var i=0; i < listModel.count; i++)
if (foodsModel.get(i).quantity==0) { listModel.remove(i) }
}@Well it works but seems like deletes not all zeros at once, with 6 total it removes 3, then 2, then 1...
What am I doing wrong? how to make sure the function removes all of them from the first click?? -
You check 'foodsModel' for 'quantity==0' and then remove an element from 'listModel' ???
-
For this code:
@function removeZeroQuantity() {
var i = 0
for (var i=0; i < listModel.count; i++)
if (listModel.get(i).quantity==0) { listModel.remove(i) }
}@
Your index is no more valid after removing an element from the list. -
Trick when removing items from a container while iterating over that container: iterate backwards, from the end to the beginning. That way, your indices will stay valid.
-
@Andre Thank you for this trick! This made my day (regarding coding) :)
-
heheh - indeed! Super!!