简体   繁体   中英

Filter a 2d Array in JS

I have a simple 2d array containing x, y coordinates like this:

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? 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. 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 .

You can use the function filter as follow:

 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

An approach using 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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