链接多个过滤器(如果存在条件)

时间:2018-07-13 15:54:06

标签: javascript

我正在尝试根据两个也可能为空的参数范围(数组)链接两个过滤器,因此f.ex可能会出现。 speedlimit=[]

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}
  ];


if (speedfilters) {
  return cars.filter(function (car) {
    return car.maxspeed >= speedfilter[0] && car.maxspeed <= speedfilter[1];
  })
} else if (pricefilter) {
  return cars.filter(function (car) {
    return car.price >= pricefilter[0] && car.price <= pricefilter[1];
  })
}
else return cars

上面示例中的结果应输出{name:'Ferrari', speed:240, price: 100}

使用JavaScript filter的方式是什么?预先感谢!

2 个答案:

答案 0 :(得分:2)

您可以通过原型继承创建一个filterCar方法

Array.prototype.filterCar = function(feature, range) {
   return this.filter((el) => {
     // is the range defined?
     if (!!range.length) {
        return el[feature] >= range[0] && el[feature] <= range[1];
     }
     else {
        return true;
     }
   })
};


var cars = [
  {name:'Ferrari', speed:240, price: 100},
  {name:'Porsche', speed:220, price: 90},
  {name:'Bugatti', speed:300, price: 500}
 ];

var result1 = cars.filterCar('speed', [240, 300])
                  .filterCar('price', [80, 120]));

var result2 = cars.filterCar('speed', [ ])
                  .filterCar('price', [80, 120]));



console.log(result1); // [{name: "Ferrari", speed: 240, price: 100}]

console.log(result2); /* [{name: "Ferrari", speed: 240, price: 100}, 
                         {name: "Porsche", speed: 220, price: 90}] */

答案 1 :(得分:1)

您可以将过滤器包装成可重复使用的方法,这可以说明过滤器不可用。

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);