Reputation: 356
I want to compare each element of two arrays, when an element does not match in both of them, it gets pushed to another array.
Both array are of indefinite size.
Example:
//namelist will always have the values present, userlist will check if it has the elements in namelist, otherwise send to another array.
namelist = ['user1','user2','user3','user4','user5']
userlist = ['user4','user1','user3'] //'user2' and 'user5' are not present
//Does not work
let arr1 = [];
let arr2 = [];
for(let i = 0; i < namelist.length && userlist.length; i++){
if(namelist[i] == userlist[i]){
arr1 = userlist[i]
} else {
arr2 = userlist[i]
}
}
console.log(arr2);
Upvotes: 0
Views: 44
Reputation: 3529
Iterate on namelist
and check item from this array exists in userlist
using Array.includes
. If false
add to result
array.
const namelist = ['user1','user2','user3','user4','user5'];
const userlist = ['user4','user1','user3'];
let result = [];
namelist.forEach(name => {
if(!userlist.includes(name)){
result.push(name);
}
});
console.info('result::', result);
Upvotes: 1