Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter subarrays in an array

I must be losing my mind. Suppose I have an array of arrays. I want to filter the subarrays and end up with an array of filtered subarrays. Say my filter is "greater than 3". So

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

After some underscore jiggery-pokery failed, I tried regular for loops.

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)
    }
  }
}

But this only removes the 1 from the first subarray. I would have thought that splice mutates the underlying array, and the length will be updated to account for that, but maybe not? Or maybe something else entirely is going wrong. Probably obvious; not seeing it. Any fancy or simple help gratefully accepted.

like image 838
rswerve Avatar asked Aug 30 '26 23:08

rswerve


2 Answers

This might do it;

var nested = [[1,2],[3,4],[5,6]],
     limit = 3,
    result = nested.map(a => a.filter(e => e > limit ));
console.log(result);
like image 182
Redu Avatar answered Sep 01 '26 13:09

Redu


If you don't have ES6 :

var nested = [[1,2],[3,4],[5,6]];

nested.map(
  function(x) {
    return x.filter(
      function(y){
        return y > 3
      }
    )
  }
)
like image 31
Gilles Quenot Avatar answered Sep 01 '26 12:09

Gilles Quenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!