简体   繁体   中英

In jQuery, how can I in an each loop remove array elements dynamically?

Let's say I have an array :

var arr = [1,2,3,4,5];

and I'm looping them with jQuery.each:

$(arr).each(function(index, value){
    if (somethingIsTrue){
        // Based on if "somethingIsTrue" I want to remove this particular item from the array at this point
    }
});

How can I achieve this?

var arr = [1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11, 12];
var arr1 = []   //make a separate array to store numbers fulfilling specified condition

$.each(arr,function(i,v){
    if(somethingIsTrue){
    arr1.push(v)  //fill second array with required numbers fulfilling specified condition
    }
});

Working Demo

OR

var arr = [1,2,2,2,3,4,5,5,5,6,7,8];
var filteredarr = $.map(arr,function (value,index) {
  return (somethingIsTrue ? value : null)
});

'filteredarr' will be a another array having numbers satisfying the condition.

Working Demo

OR

Try .splice() as shown :

var arr = [1,2,3,4,5];

$(arr).each(function(index, value){
  if(somethingIsTrue){
    arr.splice(index,1)
  }
});

Working Demo

OR

$.each(arr,function(i,v){
  if(somethingIsTrue){
  var i1 = arr.indexOf(v);
    arr.splice(i1,1);
  }
});

Working Demo

NOTE :- Last two answers will work absolutely fine if array do not contains repeating numbers(as questioner specified in question) and first two answers will work in any scenario.

There are a number of problems with the way you're trying to go about this. You shouldn't use $(arr) on an array of numbers, and you shouldn't remove elements from an array while you are iterating through it. That's a surefire recipe for buggy code.

Instead of jQuery and each() , you should use Array.prototype.filter (you can also use $.grep() if you need to support older browsers or absolutely want to use jQuery):

var filtered = arr.filter(function (value) {
    return !somethingIsTrue;
});

After this is called, filtered will be an array containing all the items where somethingIsTrue is not true (which is what I think you are asking for).

As stated above, jQuery each is not the tool to use here, but in general you should only use $(arr) when arr contains only DOM elements. To iterate over an ordinary array in jQuery, use $.each(arr, callback) .

working example

try this fiddle, http://jsfiddle.net/devools/35aysq6t/

var arr = [1, 2, 3];


$(arr).each(function (index, value) {
    if (value = 2) {
        arr = jQuery.grep(arr, function(value) {
            return value != 2;
        });
    }
});

$(arr).each(function (index, value) {
    $('.array').append(value + ',');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM