I'm working with an object with keys that have one boolean value. I'm trying to figure the most efficient way to check if any values I receive from an array equal false in the object with their associated key.
For example I have an object like so:
cars = {
bmw: true,
lexus: true,
audi: false,
mercedes: false
}
Then I'll receive an array like:
allApproved(['bmw', 'audi']) // should return false
allApproved(['bmw', 'lexus']) // should return true
If any of the values for the key false
in the map, I want my function to return false. Doesn't matter how many, if any are false I want to return false. If they are all true, I will return true.
Use Array#every
The
every()
method tests whether all elements in the array pass the test implemented by the provided function.
var cars = { bmw: true, lexus: true, audi: false, mercedes: false }; function allApproved(arr) { return arr.every(function(el) { return cars[el]; }); } console.log(allApproved(['bmw', 'audi'])); console.log(allApproved(['bmw', 'lexus']));
cars = { bmw: true, lexus: true, audi: false, mercedes: false } function allApproved(arr) { return !arr.some(function(v) { return !cars[v]; }); } console.log(allApproved(['bmw', 'audi'])); // false console.log(allApproved(['bmw', 'lexus', 'asd'])); // true
If there are not .some()
elements in the array that don't have a corresponding true
value then all are approved. (Noting that if cars
doesn't have an entry for a particular brand then this code will treat that brand as false
.)
The fastest would still be a regular old loop
function allApproved(arr) {
for (var i=arr.length; i--;) {
if (cars[arr[i]] === false) return false;
}
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.