开发者问题收集

通过检查多个条件来过滤 JavaScript 数组

2016-04-27
7176

我的数组为:

819143243

和变量:

969561689

我想使用阵列 过滤 条件,例如 获取具有 得分 的记录小于40, 状态 = 1和 perse_name 作为“心力衰竭”。

问题是,给定3个变量是 dynamic过滤器 ,如果其值为''。

我该如何实现?

2个回答

类似这样:

arr.filter(function(item) {
    var ok = true;

    if (score !== '') {
        ok = item.score < score;
    }

    if (ok && population !== '') {
        // check it
        ok = item.populations.map(function() {return item.population_name;}).indexOf(population) > -1;
    }

    if (ok && status !== '') {
        // check status
    }

    return ok;
});
Evan Trimboli
2016-04-27
var arr = 
[
    {
        "id":3,
        "status": 1,
        "first_name":"Laila",
        "last_name":"McCaine",
        "gender":"female",      
        "populations":[{"population_name":"Heart failure"}, {"population_name":"AMI"}],
        "score": 55.0
    },
    {
        "id":5,   
        "status": 1,
        "first_name":"Riva",
        "last_name":"Rontgen",
        "gender":"female",
        "populations":[{"population_name":"Pnumonia"}],
        "score": 85.0
    },
    {
        "id":8,
        "status": 0,
        "first_name":"Emily",   
        "last_name":"Rosewood",
        "gender":"female",  
        "populations":[],
        "score": 25.0
    }
];

function filterRecords( arr ){
  return arr.filter(function( record ){
    return record.score > 40 && record.status && (record.populations.filter(function( population ){
      return population.population_name == 'Heart failure';
    })).length;
  });
}

console.log( filterRecords( arr ) );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
synthet1c
2016-04-27