Reputation: 180
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?
Upvotes: 0
Views: 727
Reputation: 13381
If you want use in you need a bit change you validIds
var validIds = validUsers.reduce(function (acc,user) {
acc[user.id]=true;
return acc;
},{});
function checkValidUsers(validUsers) {
var validIds = validUsers.reduce(function (acc,user) { acc[user.id]=true; return acc; },{});
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 }]);
document.getElementById('res').innerHTML = check([{ id: 2 }, { id: 3 }]);
<div id="res"></div>
Upvotes: 1
Reputation: 160853
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; });
Upvotes: 2
Reputation: 5056
in
can be used like this with coffeescript, but in JS, it's just a iterator operator. Try with:
return ids.every(function (id) { return ~validIds.indexOf(id); });
There are some missing/wrong characters in your code, here is a complete working code:
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 ~validIds.indexOf(id); });
};
}
var check = checkValidUsers([
{ id: 1 }, { id: 2 }, { id: 3 }
]);
check([{ id: 2 }, { id: 3 }]);
Upvotes: 1