Ben Ben - 4 months ago 7
Javascript Question

Most efficient way to check if any values from an array are false based on object map

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.

Answer

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