I want to create a condition which executes the function only when all elements in the array are with status 3, if the array has an element with status 3 or different from 3 I should not execute the function.
I tried this code but doesn't work when I have element with status 3 ore different status.
goToPeople(): void {
const selectedItems = this.ms.selectedItems;
selectedItems.forEach(item => {
if (item.status !== 3){
console.log('nonnnnnn');
}else{
console.log('yesss');
//my function
}
});
}
This is JSON:
[
{
"date": "2021-10-14T16:48:05 00:00",
"status": 3,
"name": "HRDD",
"id": "ab8d4bd7"
},
{
"date": "2021-10-14T16:55:05 00:00",
"status": 2,
"name": "ddfgdfgd",
"id": "adfgdfgdf45"
}
]
CodePudding user response:
I don't know if it's the best way to do it, but this is how I usually handle situations like this (forgive syntax errors, I've only written JS not TS):
let execute = true;
selectedItems.foreach(item => {
if(item.status !== 3){
execute = false;
}
});
if(execute) console.log('yes');
else console.log('nonnnnnn');
Basically just keep a bool that toggles off if any element fails to meet your condition.
CodePudding user response:
Reduce should get you what you want...
const execute = selectedItems.reduce((acc, item) => {
if (acc === false) return;
return item.status === 3;
}, true);
This will go through each item in the array. If they are ALL 3, it will return true. If any are not, it will return false. Edge case, if the array is empty, it will return true. So you need to account for that.
CodePudding user response:
You can create a fucntion like this:
statusValid(selectedItems): boolean {
var valid = true
selectedItems.forEach(item => {
if (item.status !== 3){
valid = false;
}
});
return valid;
}
and then:
goToPeople(): void {
const selectedItems = this.ms.selectedItems;
if(statusValid(selectedItems )){
// your function here
}
}
CodePudding user response:
You can try this.
goToPeople(): void {
const selectedItemsFIlterd = this.ms.selectedItems.filter(selected => selected.status === 3);
selectedItemsFiltered.forEach(item => {
this.yourFunction();
});
}
I hope this help you, regards.
CodePudding user response:
the array every
function is used for this purpose, it returns true
if every element in the array matches the condition, otherwise false
, so:
if (selectedItems.every(item => item.status === 3)) {
// execute
}