0

Objective

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.

Code So Far

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);
4
  • How do you want to handle dupes like ["a", "b", "a"] and ["a", "a", "a"]? What's the expected output for the given arrays? Commented Sep 27, 2020 at 14:33
  • Do you expect an array which contains namelist items not found in userlist array? Commented Sep 27, 2020 at 14:40
  • @ambainBeing, Yes exactly. Commented Sep 27, 2020 at 16:08
  • @ggorlen, there will be no dupes, because I am extracting from a database, so there wouldn't be any dupes. Commented Sep 27, 2020 at 16:09

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.