按多个匹配值过滤数组

时间:2016-11-30 02:59:35

标签: javascript jquery arrays json

我一直在搜索stackoverflow问题,试图了解如何通过多个匹配值过滤数组。

我的阵列:

[{"time":"2016-11-30 02:45:00","signal":"Buy","symbol":"AUDNZDecn","price":"1.04605","timeframe":"M15","epoch":"1480473900","candel":"M151480481100"},{"time":"2016-11-30 02:41:00","signal":"Sell","symbol":"AUDJPYecn","price":"84.08700","timeframe":"M1","epoch":"1480473660","candel":"M11480480860"},{"time":"2016-11-30 02:24:59","signal":"Buy","symbol":"EURNZDecn","price":"1.48820","timeframe":"M5","epoch":"1480472699","candel":"M51480479900"}]

您可以看到有3个时间范围:M1,M5,M15

我可以使用以下代码按单个“时间范围”进行过滤:

var j = j.filter(function(el) {
            return el.timeframe == timeframe;
});

注意: j等于来自AJAX查询的JSON解析服务器响应,该查询与php脚本对话,后者传回JSON响应,即上面的数组。

目标:我想要了解的方法是一次过滤数组的多个“时间帧”值,以便当用户点击任意组合的复选框时三个时间帧,我可以从复选框中提取值,并通过用户选择的任意复选框组合过滤数组。恩。 “M1”,“M5”,“M15”,“M1,M5”或M1,M15“或M5,M15”或“M1,M5,M15”等。

返回/过滤的新数组将传递给每个循环的jquery,然后将遍历数据并将数据附加到div。 (我已经有了这部分工作)

感谢任何指导!

1 个答案:

答案 0 :(得分:1)

您可以合并Array.prototype.filterArray.prototype.some来过滤结果 - 请参阅下面的演示:



var array = [{"time":"2016-11-30 02:45:00","signal":"Buy","symbol":"AUDNZDecn","price":"1.04605","timeframe":"M15","epoch":"1480473900","candel":"M151480481100"},{"time":"2016-11-30 02:41:00","signal":"Sell","symbol":"AUDJPYecn","price":"84.08700","timeframe":"M1","epoch":"1480473660","candel":"M11480480860"},{"time":"2016-11-30 02:24:59","signal":"Buy","symbol":"EURNZDecn","price":"1.48820","timeframe":"M5","epoch":"1480472699","candel":"M51480479900"}];

function filterResults(arr) {
  return array.filter(function(el) {
    return arr.some(function(e) {
      return el.timeframe == e;
    });
  });
}

// pass the required timeframes to filter here
var result = filterResults(['M1','M5']);

console.log(result);

.as-console-wrapper{top:0;max-height:100%!important;}