Reputation: 3859
I want to look for an item in an array and if i find it then i want to remove it and then break out of the loop. This is what i have but it only jumps back to the start of the second $.each
var tempArray = dataArray;
$.each(users, function(i, val) {
var name = val.name;
// loop over each obj and match
$.each(tempArray, function(k, kval) {
if(name === kval.username){
tempArray.splice(k, 1);
return;
}
});
});
How can i jump back to the start of the first loop so that it starts iterating over the nxt name? Thanks
Upvotes: 1
Views: 2851
Reputation: 2462
Grep would grep only the values you want and discard the ones you don't want.
var persons = peopleArray;
$.each( users, function ( ii, user ) {
persons = jQuery.grep( persons , function ( person ) {
return ( person.userName !== user.name );
} );
} );
Or javascript array fn {map, filter}:
var persons= [{name: "tom", age: 22 }, { name: "jerry", age: 23 }, { name: "XXX", age: 24 }]
, bads = [{ name: "XXX", pets: 9 }, { name: "YYY", pets: 6 }];
var badnames = bads.map(function(r){ return r.name });
alert( persons.filter( function(r) {
return badnames.indexOf( r.name ) !== 0
} ).map( function ( r ) {
return r.name
} ) );
EcmaScript 6 With shorthand (lambda '=>'), you can
var badnames = bads.map(r=>r.name );
alert( persons.filter( r=> badnames.indexOf( r.name ) !== 0 ).map(r=>r.name));
result "tom,jerry"
Upvotes: 1
Reputation: 8198
We can break the $.each() loop at a particular iteration by making the callback function return false
. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
http://api.jquery.com/jQuery.each/
Upvotes: 2