📜  比较两个数组并删除不匹配的对象 - 无论代码示例

📅  最后修改于: 2022-03-11 14:58:40.056000             🧑  作者: Mango

代码示例1
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; }));
});