Filtering a Two-Dimensional Array Using JavaScript

I am working with a basic 2D array that contains x, y coordinates as shown below:

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

I want to know how I can extract pairs from the array that meet specific conditions for both x and y values, and then store those pairs in a new array. For example:

for each pair in c { 
  if (x > 3 && y > 13) {
   push to NewArray
   }
}  

I am new to JavaScript and have not been able to find a solution online. Any help would be greatly appreciated.

Answer №1

By using filter instead of push, you can achieve the desired result:

const filtered = arr.filter(([x, y]) => x > 3 && y > 13);

var arr = [
  [1, 10],
  [2, 11],
  [3, 12],
  [4, 13],
  [5, 15]
];
const filtered = arr.filter(([x, y]) => x > 3 && y > 13);
console.log(filtered);

Remember to use commas to separate array items.

The destructuring in this case is equivalent to:

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

Answer №2

To extract elements from an array that satisfy a specific condition, you can utilize the Array.prototype.filter function. For instance, if you want to filter elements where x > 3 && y > 13, you can do so using this method.

Below is an example of how you can use the filter function:

let myArray = [ [1, 10], [2, 11], [3, 12], [4, 13], [5, 15] ],
    filteredArray = myArray.filter(function([x, y]) {
      return x > 3 && y > 13
    });
    
console.log(filteredArray);

In the code snippet above (function([x, y]){}), we utilized destructuring assignment.

A different approach using arrow functions:

let myArray = [ [1, 10], [2, 11], [3, 12], [4, 13], [5, 15] ],
    filteredArray = myArray.filter(([x, y]) => x > 3 && y > 13);
    
console.log(filteredArray);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Directing to index.html using ExpressJS

JS, I am working on an express app that has various routes defined. However, I am facing an issue where if the router does not match any route, it displays index.html instead of redirecting to a specific route like '/*' as I expected. I am unsu ...

Move the cursor within the text area upon clicking the button

When the "+header" button is clicked, I am looking to automatically position the insertion point inside the text area. Currently, after pressing the button, the text box displays information like address, date, time etc. but the cursor does not start insid ...

Learn how to access the `$root` instance in Vue.js 3 setup() function

When working with Vue 2, accessing this.$root is possible within the created hook. However, in Vue 3, the functionality that would normally be placed within the created hook is now handled by setup(). The challenge arises when trying to access properties ...

In creating a loop, ensure that it skips over items when a file is not found, but breaks in the event of any other errors

My goal is to create a loop that will move on to the next item if a csv file is not found, but stop if any other error occurs after reading the csv file. The current code iterates through all items in the loop (1:5), skipping items without a corresponding ...

How can I modify the date format using the Google Ajax Feed API?

Currently, I am utilizing Google's AJAX Feed API to pull data from an RSS feed. However, I am curious about how to modify the date format. The current format fed by "datePublished" appears as follows: Sun, 29 Jan 2012 23:37:38 -0800 Is there a way t ...

Learn to save Canvas graphics as an image file with the powerful combination of fabric.js and React

I am currently utilizing fabric.js in a React application. I encountered an issue while attempting to export the entire canvas as an image, outlined below: The canvas resets after clicking the export button. When zoomed or panned, I am unable to export co ...

What could be the reason for the failure of the async await implementation in this particular code sample?

While attempting to follow a tutorial on YouTube, I encountered an issue where the code didn't work as expected. Can anyone lend a hand in helping me figure out what might be going wrong? let posts = [ {name: '1', data: 'Hi1'}, ...

The puzzling case of Java 8 arrays: why do empty arrays have a length of 1?

This code is designed to count words in a file. Each empty line adds +1, even if a line full of whitespace should split into an empty array. import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; imp ...

Eliminating the table header in the absence of any rows

I have successfully implemented a Bootstrap table in my React application, where users can add or delete rows by clicking on specific buttons. However, I want to hide the table header when there are no rows present in the table. Can anyone guide me on how ...

Avoid activating jQuery functions based on certain screen widths for menu/navigation system

Recently, I've delved into the world of jQuery and attempted to create a simple menu system. The menu is designed to expand its submenu when hovering over the list item at screen widths larger than 480px, and to expand when clicking on the list item a ...

Localizing Dates in JavaScript

I'm currently dealing with localization and globalization in an ASP.NET application. As I navigate through this process, I am encountering difficulties in getting the Date() function in JavaScript to function correctly based on the user's locatio ...

What reasons might lead an object to be passed to a view as the exact term 'object' in Express.js?

Using nodejs, express, and ejs. I have a variable called 'result' which is properly defined. When I use console.log(result) within the router.get function on my index page, it outputs a correctly structured array of objects. After that, I rende ...

The IsArray() function in IE8 encounters an issue where it expects an error object

I am interested to know why IE8 is having trouble with this line of code: if (isArray(obj)) When I check in the IE8 javascript console, I see the following: >>obj {...} >>typeof(obj) "object" >>Object.prototype.toString.call(obj) "[obj ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

Vue fails to reflect changes in data when it is updated

I have a page where I can access data by calling domain.com/subpage?soundfile=something Using the fetch method, I extract the query parameter from the URL to retrieve the necessary information. The retrieval process is successful as indicated by the data ...

The Express server's `GET` request at the root does not seem

When I access localhost:8080/chat?k=1&d=1, the console displays "CHAT PAGE" and everything works correctly. However, when I try to visit localhost:8080, the root event does not display "INDEX PAGE" as expected. Instead, it automatically retrieves ind ...

Using an array as a parameter in a function call

Looking to transfer an empty array from the main function to a user-defined function in Python. Within the function, user inputs will be added to the array and then returned to the main function upon calling. The inputs will be in string format. As a newc ...

Encountering an error saying "Cannot read property 'x' of null when using Google Charts LineChart"

When I hover over the legend labels on my Google chart, I keep getting an error message that says "Cannot read property 'x' of null," and I'm not sure why. The data is all in JSON format from an AJAX GET request and does not contain any nul ...

individualized django models field for each user

Is it possible to create a boolean field in the post model to track if a user has liked a post? This field should only be changed by the respective user and not affect others. For example, if user 1 likes a post, it should show as true only for that user ...

How can I retrieve the identifier in Socket.io?

Is there a way to retrieve the unique Id from the server using socket.io? I attempted using clients[socket.id] = socket; However, I encountered an error stating: connections property is deprecated. use getconnections() method Does anyone have any sugg ...