samedi 13 août 2022

Limit number of Array.filter() and randomise results

I have an App where you can select a muscle and a number of exercices for this muscle. It will generate a program for the gym.

Here is my code after the visitor selected a muscle and a number of exercices he wishes.

const generateProgram = () => {
    if (program) {
      for (let i = 0; i < program.length; i++) {
        const muscle = Object.keys(program[i])[0];
        const numberOfExercices = Object.values(program[i])[0];

        const dataAsker = exercices.filter(
          (exercice) => exercice.id === muscle
        );

        console.log(dataAsker);
      }
    }
  };

The console.log returns this Array : console.log

So this works fine. Now, I'd like to get from this filter only the number of items corresponding to numberOfExercices and randomly.

I tried to make another for (let j = 0; j < numberOfExercices; j++ but I still got the 10 objects.

How is this possible please ?

PS : program is just a state containing the muscle to work and the number of exercices based on visitor selection. For this exemple, program is {Abdominaux, "0"}.




Aucun commentaire:

Enregistrer un commentaire