Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item[i] from jQuery each loop

How do I remove an item[i] from items once it reaches in:

$.each(items, function(i) {     // how to remove this from items }); 
like image 511
bcm Avatar asked Feb 01 '11 23:02

bcm


People also ask

How do I break out of each loop in jQuery?

We can break the $. each() loop [..] by making the callback function return false. BTW, continue works like this: Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

How do I delete an object in forEach?

To remove element from array in forEach loop with JavaScript, we can use the array splice method. const review = ["a", "b", "c", "b", "a"]; review. forEach((item, index, arr) => { if (item === "a") { arr. splice(index, 1); } });

How do I remove an array from a forEach loop?

Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable. The behavior of this function depends on different things.

How do I remove something from jQuery?

To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.


2 Answers

It would be better not to use $.each in this case. Use $.grep instead. This loops through an array in pretty much the same way as $.each with one exception. If you return true from the callback, the element is retained. Otherwise, it is removed from the array.

Your code should look something like this:

items = $.grep(items, function (el, i) {     if (i === 5) { // or whatever         return false;     }      // do your normal code on el      return true; // keep the element in the array }); 

One more note: this in the context of a $.grep callback is set to window, not to the array element.

like image 96
lonesomeday Avatar answered Sep 21 '22 07:09

lonesomeday


I'm guessing you want $.map. You can return null to remove an item, and not worry about how indices might shift:

items = $.map(items, function (item, index) {     if (index < 10) return null; // Removes the first 10 elements;     return item; }); 
like image 25
David Tang Avatar answered Sep 22 '22 07:09

David Tang