Search code examples
javascriptarraysfunctiondynamic-arrays

Array.every returns false instead of true


I'm working on something and I wrote this code that seems to return false instead of true:

function checkValidUsers(validUsers) 
{
    var validIds = validUsers.map(function (user) { return user.id; });

    return function (users) 
    {
        var ids = users.map(function (user) { return user.id; });
        return ids.every(function (id) { return id in validIds; } );
    }
}

var check = checkValidUsers([{ id: 1 }, { id: 2 }, { id: 3 }]);

check([{ id: 2 }, { id: 3 }]);    // return false

The two map functions return the correct arrays ([1,2,3] for the first and [2,3] for the second), But every function does not for some reason.

Can anyone help me find the bug in the code?


Solution

  • Don't use in to check whether an element in an array.

    Instead , use .indexOf method.

    return ids.every(function (id) { return validIds.indexOf(id) != -1; });