2

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.

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This is a very elegant answer.
Can you explain what the destructuring assignment is? the OP probably doesn't know about it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.