Creating a workout tracker using React and Ruby on Rails. In my db, A routine has many exercises and an exercise has many routines via the exercise_sets join table. Exercise_set belongs to a routine and an exercise. I want to filter this array of exercises to show only one of each instead of five. Sorry for the noobness but what are some ways I could return ["Lat Pulldown", "Plate-Loaded Row", and "Bent-Over Dumbbell Row"]?
I’m currently getting my lists via the RoutineSerializer by declaring has_many :exercise_sets and has_many :exercises
Image of a routine's exercise_sets and exercises
CodePudding user response:
You can do this in ReactJs using Javascript:
Option 1:
loop through the excercise_sets array and save the elements into a new array and validate that the excercise_id is not repeated:
let result = [];
excercise_sets.forEach(mapItem => {
if (
!result.find(resultItem => resultItem.excercise_id === mapItem.excercise_id)
) {
result.push(mapItem);
}
});
console.log(result);
Option 2:
Use reducer to create a new accumulative array whit the same logic, checking that the current excercise_id don't exist in the accumulated array
const result = excercise_sets.reduce(
(accumulated, currentElement) =>
accumulated.every(({excercise_id}) => excercise_id != currentElement.excercise_id) //evaluates if no element already has this exercise id
? [...accumulated, currentElement] //true - if none have it, add the old elements with the new one
: accumulated, //false, keep the items you already have
[excercise_sets[0]]
);
console.log(res);