April 28, 2011

cmer4 cmer4
Lab Rat
109 posts

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

  1.             function removeZeroQuantity() {
  2.             var i = 0
  3.             for (var i=0; i < listModel.count; i++)
  4.             if (foodsModel.get(i).quantity==0) { listModel.remove(i) }
  5.             }

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??

5 replies

April 29, 2011

Aleskey78 Aleskey78
Lab Rat
31 posts

You check ‘foodsModel’ for ‘quantity==0’ and then remove an element from ‘listModel’ ???

April 29, 2011

Aleskey78 Aleskey78
Lab Rat
31 posts

For this code:

  1. function removeZeroQuantity() {
  2. var i = 0
  3. for (var i=0; i < listModel.count; i++)
  4. if (listModel.get(i).quantity==0) { listModel.remove(i) }
  5. }

Your index is no more valid after removing an element from the list.

April 29, 2011

Andre Andre
Area 51 Engineer
6031 posts

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.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

April 29, 2011

secretNinja secretNinja
Lab Rat
141 posts

@Andre Thank you for this trick! This made my day (regarding coding) :)

April 30, 2011

cmer4 cmer4
Lab Rat
109 posts

heheh – indeed! Super!!

 
  ‹‹ Can I make QML based apps persistent?      [Solved] Filtering data in XMLListModel ››

You must log in to post a reply. Not a member yet? Register here!