2016-10-05 39 views
0

我一定會失去理智。假設我有一個數組數組。我想過濾子數組,最後得到一組過濾的子數組。假設我的過濾器「大於3」。所以在一個陣列中過濾子陣列

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

在一些下劃線jiggery-pokery失敗後,我試着定期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。我會認爲拼接變異了底層數組,並且長度將被更新以解釋這個,但是可能不是?或者也許其他的事情完全出錯了。可能很明顯;沒有看到它。任何幻想或簡單的幫助感激地接受。

+2

'nested.map(ARR => arr.filter(X => X <= 3))' – vlaz

+1

此外,更具體地說,你的實現失敗,因爲當你拼接數組_decreases_,但你仍然保持循環從相同的位置 – vlaz

+0

謝謝。就是這樣。 – rswerve

回答

3

這可能會;

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

+0

可能與@ vlaz的評論重複 –

+0

@HappyCoding我不這麼認爲。 – Redu

2

如果沒有ES6:

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

nested.map(
    function(x) { 
    return x.filter(
     function(y){ 
     return y > 3 
     } 
    ) 
    } 
)