compare two arrays and remove not matched objects

If you're looping over array1 with i = 0, len = array1.length; i < len; i++,
but within the loop you remove an entry from array1 what do you think happens
on the next loop?

You also appear to be removing things that are found, but your question say
you want to remove ones that aren't. In the below, in light of your comment,
I'm removing things that aren't found.

In that case, use a while loop. I'd also use Array#some (ES5+) or Array#find (ES2015+)
rather than doing an inner loop:

var i = 0;
var entry1;
while (i < array1.length) {
    entry1 = array1[i];
    if (array2.some(function(entry2) { return entry1.Id === entry2.Student.Id; })) {
        // Found, progress to next
        ++i;
    } else {
        // Not found, remove
        array1.splice(i, 1);
    }
}
Or if it's okay to create a new array, use filter:

array1 = array1.filter(function(entry1) {
    return array2.some(function(entry2) { return entry1.Id === entry2.Student.Id; }));
});

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source