I am struggling to filter an array in one of my react projects.
My React App has a search bar that returns a searchQuery as a string and menu of movement patterns that when clicked gets added to the pattern array. The user should be able to:
- type in a search query and filter the array
- use the menu to select multiple pattern options to filter array
- filter the exercise array with both search and menu selection.
const searchQuery = "ben";
const pattern = [];
const exercises = [
{
name: "bench press",
movement: ["push", "pull", "squat", "hinge"]
},
{
name: "squat",
movement: ["push", "pull", "squat", "hinge"]
},
{
name: "squat",
movement: ["squat", "hinge"]
},
{
name: "pushup",
movement: ["push", "pull", "squat", "hinge"]
},
{
name: "pullup",
movement: ["pull", "squat", "hinge"]
},
{
name: "bent over row",
movement: ["push", "pull", "hinge"]
}
];
let filteredExercises = [];
if (searchQuery && pattern) {
filteredExercises = exercises.filter(
exercise =>
exercise.name.toLowerCase().indexOf(searchQuery) !== -1 &&
exercise.movement.some(movement =>
pattern.some(pattern => pattern == movement)
)
);
} else if (pattern.length > 0) {
filteredExercises = exercises.filter(exercise =>
exercise.movement.some(movement =>
pattern.some(pattern => pattern == movement)
)
);
} else if (searchQuery) {
filteredExercises = exercises.filter(
exercise => exercise.name.toLowerCase().indexOf(searchQuery) !== -1
);
console.log(filteredExercises);
}
console.log(filteredExercises);
The first two conditional statements work and return the correct data. As soon as I add the third conditional statement to filter by searchQuery I get an empty array in return.
Can anyone help with this?
searchQuery && patternwill always return true unless pattern is empty. You should usesearchQuery && pattern.length