Answers for "compare two arrays objects which not found remove"

1

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; }));
});
Posted by: Guest on January-30-2021

Code answers related to "compare two arrays objects which not found remove"

Browse Popular Code Answers by Language