过滤数组中的子数组

Filter subarrays in an array

本文关键字:数组 过滤      更新时间:2023-09-26

我一定是疯了。假设我有一个数组的数组。我想过滤子数组最后得到一个由过滤后的子数组组成的数组。假设我的过滤器是"大于3"。所以

let nested = [[1,2],[3,4],[5,6]]
 // [[],[4][5,6]]

在一些下划线欺骗失败后,我尝试了常规的for循环。

for (var i = 0; i < nested.length; i++){
  for (var j = 0; j < nested[i].length; j++){
    if (nested[i][j] <= 3){
      (nested[i]).splice(j, 1)
    }
  }
}

但是这只从第一个子数组中删除1。我本以为splice会改变底层数组,并且长度将被更新以解释这一点,但也许不是?或者可能是其他地方完全出了问题。可能明显;没有看到它。感谢您的帮助。

可以;

var nested = [[1,2],[3,4],[5,6]],
     limit = 3,
    result = nested.map(a => a.filter(e => e > limit ));
console.log(result);

如果你没有ES6:

var nested = [[1,2],[3,4],[5,6]];
nested.map(
  function(x) {
    return x.filter(
      function(y){
        return y > 3
      }
    )
  }
)