I want to implement a filter like this:
Where according to the selected checkbox I filter the values of an array of numbers.
For example with the following array array = [180, 210, 250, 290, 350]
:
- If I only have the first condition selected (<100) the result would be an empty array.
- If I select the second condition (between 100 and 200) and the fourth condition (>300) the result would be [180, 350]
I have the following proposed function that could handle this issue, however I feel the code is too long and complicated.
JS
function filtrarNumeros (array, c1, c2, c3, c4) {
/*c1 al c4 son booleanos que representan si se selecciono la condición de filtro */
// f1 al f4 son los resultados de cada filtro
// al final se concatenan
let f1 = []
let f2 = []
let f3 = []
let f4 = []
if (c1) {
f1 = array.filter(numero => {
return numero < 100
})
}
if (c2) {
f2 = array.filter(numero => {
return (numero >= 100 && numero < 200)
})
}
if (c3) {
f3 = array.filter(numero => {
return (numero >= 200 && numero < 300)
})
}
if (c4) {
f4 = array.filter(numero => {
return (numero >= 300)
})
}
if ([c1, c2, c3, c4].every(e => e === false)) {
return array // si no hay nada seleccionado devuelve el mismo array
} else {
return f1.concat(f2, f3, f4)
}
}
I would appreciate your help to have a more elegant and readable version that allows me to solve this problem.