I have an array objects. Inside that i want to check all selected values are true or not. below code is not working. How to check in typescript or javascript.
ngOnInit() {
let arr1 = [
{
name: 'test1',
selected: true,
},
{
name: 'test1',
selected: true,
},
{
name: 'test1',
selected: true,
},
];
let arr2 = [
{
name: 'test1',
selected: true,
},
{
name: 'test1',
selected: true,
},
{
name: 'test1',
selected: false,
},
];
console.log(this.checkallTrue(arr1));
console.log(this.checkallTrue(arr2));
}
checkallTrue(arr) {
for (const n of arr) {
if (n.selected == true) {
return true;
} else {
return false;
}
}
}
Demo: https://stackblitz.com/edit/github-7plax5-ydjwxc?file=src%2Fapp%2Fapp.component.ts
2
Answers
Your code only looks at the first element of the array, and based on that either returns true or false. The loop will never get to the second element of the array. To fix this, only return true at the end of the loop, once you’ve confirmed that they all are ok.
All you really need is
Array#every()
which checks if every item in your array matches a criteria.