如何根据一系列数字过滤数组? [英] How do I filter an array based on a range of numbers?

查看:157
本文介绍了如何根据一系列数字过滤数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数过滤器(arr,criteria){
return arr.filter(function(obj){
return Object.keys(criteria).every(function(c){
return!(criteria [c])|| obj [c] == criteria [c];
});
});


var arr = filter(arr,{dep:dv,arr:av,car:cv,epi:acv,dur:dv});

我有很多选项供用户从select中选择。持续时间,这里是我的:

 < select name =durationid =duration> 
< option selected disabled hidden value => - < / option>
< option value =l1>小于1小时< / option>
< option value =1to3> 1至3小时< / option>
< option value =3to6> 3至6小时< / option>
< option value =6to10> 6到10小时< / option>
< option value =m10>超过10小时< / option>
< / select>

但是,该过滤器基于确切的标准。我想过滤 arr 中介于1到3或6到10之间的浮点数。我还希望能够运行我在其中发现的其他过滤器,arr,car,epi,dur。有没有什么办法可以做到这一点?

解决方案

使用

  var myArray = [1,2,3,3.1,Math.PI,4,4.3,6.1]; //样本数组
//从选项值到函数的字典(JS对象像哈希表一样工作)
var options = {
l1:function(a){return a.duration <1 ;},
1to3:function(a){return a.duration> = 1&& a.duration< 3;},
3to6:function(a){return a.duration> = 3&& a.duration< = 6;},
...
//当您需要过滤数组时,请这样做:
var myNewArray = myArray.filter(
选项[document.getElementById('duration')。selectedOptions [0] .value]
);


I have an array that I filter with this function:

function filter(arr, criteria) {
    return arr.filter(function(obj) {
        return Object.keys(criteria).every(function(c) {
            return !(criteria[c]) || obj[c] == criteria[c];
        });
    });
}

var arr = filter(arr, { dep: dv, arr: av, car: cv, epi: acv, dur: dv }); 

And I have a bunch of options that the user can choose from in the select. For duration, here is what I have:

<select name="duration" id="duration">
  <option selected disabled hidden value="">-</option>
  <option value="l1">Less than 1 hour</option>
  <option value="1to3">1 to 3 hours</option>
  <option value="3to6">3 to 6 hours</option>
  <option value="6to10">6 to 10 hours</option>
  <option value="m10">More than 10 hours</option>
</select>

But that filter is based on exact criteria. I want to filter float numbers in arr that are between 1 and 3 or 6 and 10. I also want to be able to run my other filters that you see up there with dep, arr, car, epi, dur. Is there any way I can do this?

Use array.filter with a callback. The code below uses a dictionary with entries corresponding to option values.

var myArray = [1,2,3,3.1,Math.PI,4,4.3,6.1]; //sample array
//Dictionary from option values to functions (JS objects work like hashtables)
var options = {
  "l1":   function(a){return a.duration<1;},
  "1to3": function(a){return a.duration>=1 && a.duration<3;},
  "3to6": function(a){return a.duration>=3 && a.duration<=6;},
...
//When you need to filter the array, do it like so:
var myNewArray = myArray.filter(
  options[ document.getElementById('duration').selectedOptions[0].value ]
);

这篇关于如何根据一系列数字过滤数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆