retrieve the neighboring value or node located right beside in a 2D array or grid

Is there a way to modify this function so that it only returns the neighbors directly above, below, left, and right instead of including corner neighbors?

function getNeighbors(nodes, column, row) {
    var rowLimit = nodes.length - 1;
    var columnLimit = nodes[0].length - 1;

    for (let x = Math.max(0, column - 1); x <= Math.min(column + 1, columnLimit); x++) {
        for (let y = Math.max(0, row - 1); y <= Math.min(row + 1, rowLimit); y++) {
            if ((x === column && Math.abs(y - row) === 1) || (y === row && Math.abs(x - column) === 1)) {
                board.nodes[column][row].neighbours.push(nodes[x][y]);
            }
        }
    }
}

Answer №1

To optimize the code, I suggest bypassing the two nested for loops and instead directly checking for the existence of the required neighbors using conditional statements.

Below is a pseudo code example featuring a 2D array filled with strings for illustration purposes.

In this demonstration, we are searching for the adjacent nodes of nodes[2][1], which in this instance is "c1" without a bottom neighbor.

let nodesExample = [
  ["a0", "a1", "a2"],
  ["b0", "b1", "b2"],
  ["c0", "c1", "c2"],
]

function getNeighbors(nodes, column, row) {
  let neighbours = []

  //top
  if (column > 0 && nodes[column - 1][row]) {
    neighbours.push("top: " + nodes[column - 1][row]);
  }

  //bottom
  if (column < nodes.length - 1 && nodes[column + 1][row]) {
    neighbours.push("bottom: " + nodes[column + 1][row]);
  }

  //left
  if (nodes[column][row - 1]) {
    neighbours.push("left: " + nodes[column][row - 1]);
  }

  //right
  if (nodes[column][row + 1]) {
    neighbours.push("right: " + nodes[column][row + 1]);
  }

  return neighbours
}

console.log(getNeighbors(nodesExample, 2, 1))

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

What is preventing the specific value in React state from being updated?

Starting off as a beginner, but I'm giving it a shot: In my React project, users input landing pages and I aim to extract data from these pages using JQuery and RegEx, then update the state with the extracted value. The issue I'm facing is that ...

What is the best way for a client to showcase a constantly fluctuating server-side variable's value?

On my website's homepage (index.html), I want to show a dynamic server-side global variable called serverVariable. This variable is always changing based on the node.js server-side code. However, since the client doesn't know what serverVariable ...

Different kinds of garbage collection operations in NodeJS

When utilizing the perf_hooks module in NodeJS, we have access to information regarding garbage collection. This can be achieved by using PerformanceObserver, which is triggered with each garbage collect event. const obs = new perf_hooks.Performanc ...

High-resolution visuals and interactive scripting

I am currently using pannellum (http://www.mpetroff.net/archives/2012/08/28/pannellum-1-2/) with Three.js to work on local files. Everything works smoothly for small files, but when I try to load a 5000 x 10000 image, it fails to load. I'm wondering w ...

Incorporating a button into a list item using jQuery and triggering the click event

I need assistance in adding a simple "delete button" to each item on the list. The items contain barcodes retrieved from a table, and I want to enable delete functionality for each barcode. My ideal solution involves placing an X button in the top right c ...

What significance does the slash hold in a package name when using require for an npm package?

When we "require" non-local NodeJS modules, what does the slash in the module name signify? For instance: from the GitHub page of the ShellJS npm module (link: https://github.com/shelljs/shelljs#javascript) require('shelljs/global'); requir ...

Generate pairs of arrays using elements from two separate arrays

I have two arrays containing IDs that are related in length. When I say they are related in length, I mean that if ArrayA has a length of 4, then ArrayB will have a length equal to (ArrayA.length * (ArrayA.length - 1)) / 2 (which means if ArrayA has a leng ...

Performing element-wise multiplication of two numpy arrays

I am currently working on coding a multispectral image with 33 channels for every pixel. My task involves using two numpy arrays named image and spectral_range. As an example, I have an image that consists of 4 x 4 pixels: image = np.array([[[1,2,4,3],[ ...

What could be causing my Ionic button to not initialize in the expected state while using ngIf with a boolean property connected to an Ionic checkbox?

I'm currently in the process of setting up a list of ingredients with checkboxes and conditional buttons, but I'm facing some challenges with the default state. Ideally, I only want the button to be visible when the checkbox is unchecked so that ...

Ways to confine the movement of a draggable div in this particular scenario

Exploring the HTML Structure: HTML <div id="outer"> <div id="inner"> <div id="bounds"> <div id="myimage"> </div> </div> </div> </div> Customizing with CSS #ou ...

I need to position a Vue component at the top of the page for a specific view only

How can I ensure that the component SiteHead only appears at the very top of the HomeView page, above the SiteNavigation component? If I place the SiteHead component within the HomeView.vue code, it ends up below SiteNavigation. Here is my App.vue code: & ...

What is the process for integrating a third-party JavaScript Node.js library into a Cordova plugin?

I'm in the process of creating a Cordova plugin for an internal project and I am considering integrating a third-party open source Javascript library called bluebird promise. My initial thought was to simply copy and paste the bluebird JS files into m ...

Tips for creating a static background when displaying a modal popup in AngularJS

Incorporating a modal popup to modify a row within a grid view has been my recent task. Leveraging the row.getProperty() function, I successfully extracted the row values within the modal. However, an inconvenience emerged when attempting to edit a value ...

What's the best way to fill checkboxes in EJS when editing a route?

As a beginner, I am working on my first project - a simple content/property listings app. I have created a form to collect user data and display it on a show form. The form includes sections for checkboxes and radio buttons, with the values being stored i ...

Comment system inspired by Facebook using jQuery

Check out my jQuery comment system that I created: http://jsfiddle.net/CKqWz/. Take a look at the code below: $(document).ready(function () { $("#commentlink1").click(function () { $("#commentbox1").toggle("slow"); }); $("#commentlink2 ...

Use SheetJS to customize header order using json_to_sheet

I am currently using SheetJS within the Angular framework to export JSON data as an .xlsx file. An example of the JSON structure I am working with is shown below: [{ "ID": "E111", "Name": "John", "LastL ...

I don't understand why I keep receiving the error message "Array indices must be positive integers or logical values."

Could someone assist in identifying where the error is occurring in my code for this function? The arrays alpha_p and width contain only positive numbers. gain2 = (alpha_p.'./(1-exp(-alpha_p.'.*width.'))).*((((2.*(exp((-2.*alpha_.*(1-k)-alph ...

Troubleshooting issue with image domains in next.config.js environment configuration

Having an issue with configuring images domains in the next.config.js file. Check out the contents of next.config.js below: module.exports = { reactStrictMode: true, env: { CLIENT_LOCAL_API_URL: '/api', CLIENT_API_URL: '/api' } ...

Utilizing Material UI (mui) 5.0 within an iframe: Tips and tricks

Attempting to display MUI components within an iframe using react portal has resulted in a loss of styling. Despite being rendered within the iframe, MUI components seem to lose their visual appeal when displayed this way. Most resources discussing this is ...

Iterating variables in Vue.js is reminiscent of the process in AngularJS

When working on my application using vue.js, I am interested in finding the last repeated element within a v-for directive. I understand that in angularjs, there is a similar concept using the $last loop variable in its ngRepeat directive: <div ng-repe ...