Вы можете перенести свою фильтрацию в повторно используемый метод, и это может объяснить, что фильтр недоступен.
function filterCars(carsArray, property, rangeArray) {
// if rangeArray is not supplied, or is empty, just return the unfiltered input
if(!rangeArray|| rangeArray.length === 0) {
return carsArray;
}
// otherwise filter according to logic
return carsArray.filter(car => car[property] >= rangeArray[0] && car[property] <= rangeArray[1]);
}
Это может быть цепочка или для большей читаемости, вызванной последовательно:
function filterCars(carsArray, property, rangeArray) {
if(!rangeArray|| rangeArray.length === 0) {
return carsArray;
}
return carsArray.filter(car => car[property] >= rangeArray[0] && car[property] <= rangeArray[1]);
}
var speedfilter = []; // [240,300]
var pricefilter = [80,120]
var cars = [
{name:'Ferrari', maxspeed:240, price: 100},
{name:'Porsche', maxspeed:220, price: 90},
{name:'Bugatti', maxspeed:300, price: 500}
];
cars = filterCars(cars,"maxspeed",speedfilter);
cars = filterCars(cars,"price",pricefilter);
console.log(cars);