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

Error occurs when attempting to change the color of a dynamically generated div, resulting in the message: "Type Error: Unable to assign a value to the property '

I'm facing an issue with my code where I have a parent div that loads with a random color, and upon clicking a button, it should create a new colored div inside. However, I keep encountering the following error: TypeError: Cannot set property ' ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

JavaScript if else statement with 3 different scenarios

I'm having trouble figuring out why this code isn't working. It seems like there might be a conflict between the testRed and testGreen functions. If that's the case, could someone please suggest a better approach to solving this issue? Code: ...

Utilizing window.location.pathname in Next.js for precise targeting

Are you familiar with targeting window.location.pathname in NEXT.JS? I encountered a red error while using this code in Next.js const path = window.location.pathname console.log(path) // I am able to retrieve the pathname here Then { ...

Is it possible to list bash/sh files as dependencies in package.json?

Currently, I have a bash script named publish.sh that I use for publishing modules to npm. Since I am constantly adjusting this script, I find myself needing to update every copy of it in each npm module I manage. Is there a method to include this bash sc ...

Running two servers at the same time using nodemon might seem complex, but it

Is it possible to run two servers (www.js and apiServer.js) simultaneously using nodemon? I have set the value for the "start" key in package.json as https://i.stack.imgur.com/r8M7p.jpg After running nodemon in the command prompt with the current working ...

Issue with marker functionality on Google Maps JavaScript API when conditions are not functioning correctly

I am currently working on plotting different markers on Google Maps by extracting data from a CSV file. I have incorporated the parsecsv-0.4.3-beta library to read the CSV file, and everything is functioning smoothly except for when I compare two fields to ...

Creating an AJAX URL in an external JavaScript file within a Django project

How can I verify if a student user's email exists in the database using keyup event in a registration form, and prevent form submission if the email is already registered? Below are the relevant files for achieving this: urls.py urlpatterns = [ ...

Sending data from an AJAX POST request to a Grails Controller

Currently, I am in the process of developing a social networking platform using Grails. However, I have encountered a roadblock when it comes to allowing users on their edit profile page to input a YouTube URL into a text field. By clicking a button, a Jav ...

Guide on utilizing exported API endpoint in Node and Express

Seeking a deeper understanding of express and its utilization of various endpoints. Recently came across an example of an endpoint that reads in a json file, demonstrated as follows: const fs = require('fs'); const path = require('path&apos ...

When invoking a native prototype method, consider extending or inheriting object prototypes for added functionality

Recently, I came across a discussion on Inheritance and the prototype chain where it mentioned: Avoiding bad practice: Extension of native prototypes One common mis-feature is extending Object.prototype or other built-in prototypes. This practice, known ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...

Is there a way to dim and deactivate a button after it has been clicked once?

Hello, I am attempting to disable and grey out a button after it has been clicked once in order to prevent the user from clicking it again until they refresh the page. I hope my question is clear enough and that you can understand me. Below is the HTML cod ...

Guide on how to restrict specific days and dates in MUI React datepicker using a JSON array

I am working on a Laravel application that generates a JSON response containing dates and days of the week that need to be disabled in the datepicker. For instance, here is an example of my datesOff constant when I log it: ['2022-05-08', '2 ...

Preventing Angular $rootElement.on('click') from affecting ReactJS anchor tag interactions

Running both AngularJS and ReactJS on the same page has caused an issue for me. Whenever I click on a ReactJS <a> tag, Angular's $rootElement.on('click) event is triggered and the page redirects. I need to perform some functionality in Re ...

I am looking to integrate my information into the user interface using Angular

import { Component, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { Batch } from '../../../config/batchnew/batch.model'; import { BatchService } from '../../../config/batchnew ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

Issue with ESLint arises following the installation of npm create-react-app package

ESLint is showing Invalid Options: - Unknown options: env, parserOptions, rules. The 'parserOptions' has been removed and you should now use the 'overrideConfig.parserOptions' option instead. Similarly, the 'rules' have been r ...

I must add and display a tab for permissions

I am currently using the material UI tab for my project. My goal is to display the tab only when the permission is set to true. I have successfully achieved this functionality, but the issue arises when the permission is false. It results in an error that ...

Ways to verify if two items within a collection of objects share a common value in MongoDB

I have a collection of data called users stored in mongoDB that has the following structure: _id: ObjectId, sports: [ { name: 'cricket', history: [ { from: 10, to: 30 }, { from: 30, to: ...