How to Filter a 2D Array in JavaScript?

Estimated read time 1 min read

You can filter a 2D (multi-dimensional) array in JavaScript by using nested Array.prototype.filter() methods.

Here’s an example:

const originalArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

const filteredArray = originalArray.filter(arr =>
  arr.filter(num => num % 2 === 0)
);

console.log(filteredArray);
// Output: [[4, 6, 8]]

In this example, the outer Array.prototype.filter() method filters the 2D array by checking if the inner array contains at least one even number. The inner Array.prototype.filter() method filters each inner array to only contain even numbers.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply