Search code examples
javascriptarraystypescript

How to check whether a boolean value is false in every object of an array in?


I have an array which consists of multiple objects:

quesListArray = [
                   {Position: 1, Mandatory: false}, 
                   {Position: 2, Mandatory: true}, 
                   {Position: 3, Mandatory: false}, 
                   ...
                   ...
                ]

How can I get to know whether 'Mandatory' field in every object is false or not. If all are false then I need to show a message.

Any help will be appreciated. Thank you.


Solution

  • Use every with arrow function (for brevity) on questListArray, like so:

    areAllMandatoriesFalse() {
       if (this.quesListArray.every(item => !item.Mandatory)) {
         alert("All are false");
       }
       else {
          alert("Not all are false");
       }
    }
    

    DEMO