1

I have a collection of Customer objects inside the JavaScript Array.

var customer = Customer(); 
customer.firstName = "John"; 
customer.isEnabled = true 

var customer2 = Customer(); 
customer2.firstName = "Mary"; 
customer2.isEnabled = false

var customers = [customer,customer2]; 

Now, I want to return true if any of the objects inside the customers array property "isEnabled" = false. Basically I want a way to validate a property of every object that is inside the array (customers).

UPDATE:

So using the some function I can do something like this:

customers.some(e => e.isEnabled == true) 

So, now it will only return true if all the elements in the array have isEnabled property to true. Is that right?

4 Answers 4

3

What you want is Array.prototype.some or Array.prototype.every

Here is how you'd use it in your case:

var customers = [
    { firstName: "John", isEnabled: true },
    { firstName: "Mary", isEnabled: false },
];

var goodCustomers = [
    { firstName: "George", isEnabled: true },
    { firstName: "Sandra", isEnabled: true },
];

function isNotEnabled(customer) {
    return !customer.isEnabled;
}
function isEnabled(customer) {
    return customer.isEnabled;
}

customers.some(isNotEnabled);
//=> true
goodCustomers.some(isNotEnabled);
//=> false

customers.every(isEnabled);
//=> false
goodCustomers.every(isEnabled);
//=> true

Functional libraries are also excellent for this kind of problem, here's a Ramda example just for fun:

R.all(R.prop("isEnabled"), customers);
//=> false
R.any(R.compose(R.not, R.prop("isEnabled")), customers);
//=> true
Sign up to request clarification or add additional context in comments.

4 Comments

Basically it should only return true if all the items with their property isEnabled is true in the array.
Yes, I misunderstood you a bit, included another example with [].every()
Thanks! I think I worded my question poorly. Sorry for that. every() is awesome!
You're welcome. Also the lodash advice isn't bad per se, even though it's a bit overkill for your problem, it allows you to use that kind of programming style in a lot of other scenarios (and it'd be more elegant). There's Ramda also.
0

Use every method:

customers.every(function(v){ return v.isEnabled;  }); // will return true if every object 'is enabled'

Comments

0

If you are using Underscore.js, You could use _.where() function.

_.where(customers, {isEnabled: true});

Comments

-2

Checkout the lodash library. It has lots of such functions already written for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.