简体   繁体   English

在 JS 中过滤二维数组

[英]Filter a 2d Array in JS

I have a simple 2d array containing x, y coordinates like this:我有一个包含 x, y 坐标的简单二维数组,如下所示:

var c = [
        [1,10]
        [2,11]
        [3,12]
        [4,13]
        [5,15]
];

How can I extract only pairs that satisfy TWO conditions (one for x, one for y) and put those in its own array?如何仅提取满足两个条件的对(一个用于 x,一个用于 y)并将它们放入自己的数组中? For instance:例如:

for Each of c { 
  if (x > 3 && y > 13) {
   push.NewArray
   }
}  

Newbie to JS here and can't find this on the web. JS 新手,在网上找不到。 Thanks in advance for any help.在此先感谢您的帮助。

With filter instead of push, like this:用过滤器代替推送,像这样:

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

You need commas to separate array items too.您也需要逗号来分隔数组项。

The destructuring there is equivalent to:那里的解构相当于:

const filtered = c.filter((arr) => arr[0] > 3 && arr[1] > 13);

You can use the function Array.prototype.filter which executes a predicate (aka handler) in order to extract the elements in the array who satisfies a specific condition, in your case x > 3 && y > 13 .您可以使用函数Array.prototype.filter执行谓词(又名处理程序)以提取数组中满足特定条件的元素,在您的情况下为x > 3 && y > 13

You can use the function filter as follow:您可以按如下方式使用函数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);

In the code snippet above ( function([x, y]){} ), we used something called destructuring assignment在上面的代码片段( function([x, y]){} )中,我们使用了一种叫做destructuring assignment东西

An approach using arrow functions :使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM