[英]Filter a 2d Array in JS
我有一個包含 x, y 坐標的簡單二維數組,如下所示:
var c = [
[1,10]
[2,11]
[3,12]
[4,13]
[5,15]
];
如何僅提取滿足兩個條件的對(一個用於 x,一個用於 y)並將它們放入自己的數組中? 例如:
for Each of c {
if (x > 3 && y > 13) {
push.NewArray
}
}
JS 新手,在網上找不到。 在此先感謝您的幫助。
用過濾器代替推送,像這樣:
const filtered = c.filter(([x, y]) => x > 3 && y > 13);
var c = [ [1, 10], [2, 11], [3, 12], [4, 13], [5, 15] ]; const filtered = c.filter(([x, y]) => x > 3 && y > 13); console.log(filtered);
您也需要逗號來分隔數組項。
那里的解構相當於:
const filtered = c.filter((arr) => arr[0] > 3 && arr[1] > 13);
您可以使用函數Array.prototype.filter
執行謂詞(又名處理程序)以提取數組中滿足特定條件的元素,在您的情況下為x > 3 && y > 13
。
您可以按如下方式使用函數filter
:
let c = [ [1, 10], [2, 11], [3, 12], [4, 13], [5, 15]], filtered = c.filter(function([x, y])/*This is the predicate (aka handler)*/ { return x > 3 && y > 13 }); console.log(filtered);
在上面的代碼片段( function([x, y]){}
)中,我們使用了一種叫做destructuring assignment
東西
使用arrow functions
的方法:
let c = [ [1, 10], [2, 11], [3, 12], [4, 13], [5, 15]], filtered = c.filter(([x, y]) => x > 3 && y > 13); console.log(filtered);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.