javascript - compare two arrays and remove not matched objects -


i struggling compare 2 arrays of objects , removing not matched objects first array.

all need compare 2 arrays (array1 , array2) of objects , remove not matched objects array 1.

this have done till remove items.

for (var = 0, len = array1.length; < len; i++) {     (var j = 0, len2 = array2.length; j < len2; j++) {         if (array1[i].id != array2[j].student.id) {             array1.splice(j, 1);             len= array1;         }     } } 

if you're looping on array1 i = 0, len = array1.length; < len; i++, within loop remove entry array1 think happens on next loop?

you appear removing things are found, question sayd want remove ones aren't. in below, in light of comment, i'm removing things aren't found.

in case, use while loop. i'd use array#some (es5+) or array#find (es2015+) rather doing inner loop:

var = 0; var entry1; while (i < array1.length) {     entry1 = array1[i];     if (array2.some(function(entry2) { return entry1.id === entry2.student.id; })) {         // found, progress next         ++i;     } else {         // not found, remove         array1.splice(i, 1);     } } 

or if it's okay create new array, use filter:

array1 = array1.filter(function(entry1) {     return array2.some(function(entry2) { return entry1.id === entry2.student.id; })); }); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -