I have an array object. I want to check all ‘selected’ property is true or not. How to check this in javascript.
Demo: https://stackblitz.com/edit/js-xmhxzk?file=index.js
var arr1 = [
{ id:"1", selected: true },
{ id:"2", selected: true },
{ id:"3", selected: true }
];
var arr2 = [
{ id:"1", selected: true },
{ id:"2", selected: false },
{ id:"3", selected: true }
];
checkArr(arr1);
checkArr(arr2);
function checkArr(arr) {
let i = arr.length;
while (i--) {
if (arr[i].selected === true) {
alert("all selected is true from this array");
}
else if(arr[i].selected === true){
console.log("At least one selected");
}
else {
alert("No..All are not selected");
}
}
}
4
Answers
You can use a combination of
every
andsome
function to achieve your result easily. Something like:You could keep count of how many elements are selected. If that count equals the length of the array, then all were selected.
For checking all "selected" property is true then you can use "every" method. And if you want to at least one selected property is set to true then use "some".
In JavaScript, you can check if all the objects in an array have a specific property set to true by using the every method along with a callback function. Here’s an example:
In the example above, the every method is used to check if the selected property of all objects is equal to true. The every method returns true if the callback function returns true for every element in the array; otherwise, it returns false.
You can simplify the code by directly using the boolean value of the property, like this:
This checks if all objects have the selected property set to true. If any object has selected set to false or if the property is not present in any object, the result will be false.