How to find an object with a certain property value in an array?

question contest:

I have an array of objects:

var allButtons = [
    buttonA,
    buttonВ,
    buttonС,
    "->"
];

This objects can have the property ‘hidden’ which can be true or false.

I need to discover (in an optimal way), whether any of this ‘buttons’ have hidden === false (in other words, are visible).

Now i use this primitive approach:

someOfButtonsIsVisible = false;

Ext.each(allButtons, function (item){
    if(item.hidden === false) {
        someOfButtonsIsVisible = true;
    }
});

But in this case i have to go through all objects and check their ‘hidden’ property.

Is there a better way to know whether any of objects in array have hidden === false?

question comments:

answers:

answer1:

Use array.prototype.some:

var someOfButtonsIsVisible = allButtons.some(button => button.hidden === false);

It can also be done with array.prototype.every:

var someOfButtonsIsVisible = !allButtons.every(button => button.hidden === true);

But in your case, array.prototype.some make more sense

answer comments:

answer2:

Use Array.prototype.find().

The find() method returns the value of the first element in the array that satisfies the provided testing function.

Find will traverse your array, and stop once it found the value wanted. You can then test the return value if it’s different from undefined.

Edit: If your goal is to identitfy if at least one (or some) value are false, then array.some()is better. If you goal is to retrieve the value which match hidden === false then array.find() is better.

answer comments:

添加评论