Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何过滤阵列中的不同阵列_Javascript - Fatal编程技术网

Javascript 如何过滤阵列中的不同阵列

Javascript 如何过滤阵列中的不同阵列,javascript,Javascript,我正在尝试从阵列中仅筛选活动产品 过滤活动产品的最佳做法是什么?它是一个嵌套数组,因此您必须根据active==true对其进行两次过滤 请找到以下解决方案: var myArr = [ [{ product: "Test", price: 30, active: true }, { product: "Test2", price: 50, active: true }], [{ product:

我正在尝试从阵列中仅筛选活动产品


过滤活动产品的最佳做法是什么?

它是一个嵌套数组,因此您必须根据active==true对其进行两次过滤

请找到以下解决方案:

var myArr = [
    [{
    product: "Test",
    price: 30, 
    active: true
    },
    {
    product: "Test2",
    price: 50, 
    active: true
    }],
    [{
    product: "Test3",
    price: 60, 
    active: false
    },
    {
    product: "Test4",
    price: 50, 
    active: true
    }]
    ];


    var newArray = [];

        myArr.filter(function (el) {
          el.filter(function(e2)
          {
            if(e2.active)
            {
              newArray.push(e2);
            }
          }); 
        });
    console.log(newArray);
您还可以使用foreach获得结果

var newArray = [];
    myArr.forEach((val,key)=>{
      val.forEach((val1,key1)=>{
        if(val1.active)
        {
          newArray.push(val1);
        }
      });
    });
console.log(newArray);


我希望这会很有用。

首先,我会将数组展平,使每个元素都位于同一级别,然后对其进行过滤

看起来是这样的:

var activeProducts = myArr.flat().filter(item => item.active);

此解决方案短且有效,但请注意Array.prototype.flat方法尚未实现,但我相信您可以找到polyfill。

请为此输入添加预期输出。只是想知道,您使用filter而不是foreach是否有原因?
    var newArray = [];

        var singleArray = [].concat(...myArr);

        singleArray.forEach((val,key)=>{
          if(val.active)
          {
            newArray.push(val);
          }
        });

console.log(newArray);
var activeProducts = myArr.flat().filter(item => item.active);