1

I am storing a number of objects within the below array in my Typescript project

(I have removed some data to make the code easier to read):

workoutExercises = [
    {
      id: 0,
      exerciseComplete: false,
    },
    {
      id: 1,
      exerciseComplete: false,
    },
    {
      id: 2,
      exerciseComplete: false,
    },
  ];

I am trying to write some code that checks if all the exerciseComplete vaues are TRUE.

If all of them are TRUE, I want to perform a certain action. If at least one of them is FALSE, I want to perform a different action.

I'm able to loop through the objects with the below For Loop, but I'm not sure how to check all the exerciseComplete values.

for (let i = 0; i < this.workoutExercises.length; i++) {
    console.log(this.workoutExercises[i].exerciseComplete);
}

Can someone please tell me how I would check the above with this loop?

user9847788
  • 2,135
  • 5
  • 31
  • 79
  • 2
    Look at [`Array.some()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) and [`Array.everyt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every). – Ori Drori Oct 05 '20 at 19:53
  • Does this answer your question? [Check if object value exists within a Javascript array of objects and if not add a new object to array](https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add) – Heretic Monkey Oct 05 '20 at 20:52

4 Answers4

3

Use Array.every().

workoutExercises.every(exercise => exercise.exerciseComplete)

//returns true if all exercises are complete
ivanjermakov
  • 1,131
  • 13
  • 24
2

Array.every() will help you check whether all elements in the array pass or not

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

Array.every()

1
if (workoutExercises.some(item => !item.exerciseComplete)) {
    //...
} else {
    //...
}
Chawki Messaoudi
  • 714
  • 2
  • 6
  • 18
0

Create an array copy where excercises are complete and then compare both sizes

let workoutExercisesDone = workoutExercises.filter(exercise => exercise.exerciseComplete); //this will filter yout array by exercises finished

then compare if both lenght are equals

workoutExercisesDone == workoutExercises //true means that all exercises are done