Ben
Ben

Reputation: 5361

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.

Upvotes: 0

Views: 226

Answers (3)

nnnnnn
nnnnnn

Reputation: 150080

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

Upvotes: 1

adeneo
adeneo

Reputation: 318312

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

Upvotes: 0

Rayon
Rayon

Reputation: 36609

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

Upvotes: 2

Related Questions