1

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

3 Answers 3

3

Try returning false in the second loop

return false;
Sign up to request clarification or add additional context in comments.

Comments

2

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/

1 Comment

but what if you dont want to break the loop, but simply remove item[i] from the loop because it met a condition, and then continue on with your .each loop(). the documentation doesn't address that and I've seen some developers simply use return; within a conditional statement for $(this) to be removed from the loop.
1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.