navigating through a grid of elements in two dimensions

Just a heads up: I'm new to programming and I'm not expecting anyone to do my coding for me. What I really need is some guidance or examples that I can tweak to suit my project. After all, how will I learn if someone does everything for me? :=)

The issue at hand is this 2D array:

var myArray = [["pat",  "tom" , "john"], ["sam", "toby", "barbra"],["william","jack", "janice"]];

I have to navigate through the array from one row to the next (I've already written the code for modifying the rows and it's working fine).

I came across this code snippet that should help with traversing the array - moving forward (to the next row), backward (to the previous row), and staying in the current position.

var iterifyArr = function (arr) {
var cur = 0;
arr.nextRecord = (function () { return (++cur >= this.length) ? false : this[cur]; }); // move to the next row of array
arr.prevRecord = (function () { return (--cur <= this.length) ? false : this[cur]; }); // move to the previous row of array
arr.cur = (function () { return this[cur]; });
return arr;
};
var myArray = [["pat",  "tom" , "john"], ["sam", "toby", "barbra"],["william","jack", "janice"]];
iterifyArr(myArray);

But when I attempt to retrieve the current position using the following code, I end up getting the last item in the row instead of the row number itself.

var currentpos = myStack.cur();

If anyone could kindly point out where I may be making an error, I would greatly appreciate it.

Answer №1

My recommendation is to maintain the variable cur, which I have renamed to index, in a suitable location within the code. It is important to check before incrementing or decrementing its value.

function convertArray(arr) {
    var index = 0;

    arr.nextItem = function () {
        return index + 1 < this.length && this[++index];
    };

    arr.prevItem = function () {
        return index >= 1 && this[--index];
    };

    arr.currentItem = function () {
        return this[index];
    };

    arr.getIndexValue = function () {
        return index;
    };

    return arr;
};

var sampleArray = [["pat", "tom", "john"], ["sam", "toby", "barbra"], ["william", "jack", "janice"]];
convertArray(sampleArray);

console.log(sampleArray.nextItem());
console.log(sampleArray.nextItem());
console.log(sampleArray.nextItem());
console.log(sampleArray.currentItem());
console.log(sampleArray.getIndexValue());
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Exploring the "how to think about it" questions is truly rewarding for me, so please excuse the detailed explanation.

When approaching a problem like this, my initial step is to take a simplistic approach, focusing solely on the core logic without getting bogged down in unnecessary details (such as programming language specifics). By gaining a clear understanding of the problem at hand, you can more easily recognize relevant code snippets when it comes time to implement them.

Let's define "rows" within the context of a 2d grid. Consider the following code snippet:

var myArray = [["pat",  "tom" , "john"], ["sam", "toby", "barbra"],
               ["william","jack", "janice"]];

Simplifying this, let's represent it as follows: g is "grid", r is "row", and c is "column":

g = r1 ( c1, c2, c3 )
    r2 ( c1, c2, c3 )
    r3 ( c1, c2, c3 )

The pattern here is quite straightforward. Moving on to the instruction to "move forward through the rows," I interpret this as starting from a given row and progressing either forward or backward to adjacent rows (note that ES6 provides handy tools for achieving this without external libraries, such as iterators).

Here is a basic code outline (there are more efficient ways to accomplish this task functionally, but considering your familiarity with JavaScript, I'll keep it simple):

// Assuming the need to find a row index based on a value.
// We only require the index, not the actual row itself.
// This step may be skipped for the first/last row,
// as their indices would be 0 and grid.length - 1 respectively.
var findRow = function ( val ) {
   grid.forEach ( function ( row, row_i ) {
      if ( row.find ( val ) { 
         return row_i;
      }
   }
}

// Proceeding to navigate through rows
// Using 0 and 1 as valid values for "next" and "previous"
// Alternatively, separate functions like "next" and "prev" could be implemented passing 0 and 1 to this function.
var navRow = function ( row_num, direction ) {
  // Validating the direction parameter
  var validDirections = [ 0, 1 ];
  if ( ! validDirections.find ( direction ) ) {
     console.log ( 'bad direction!!!' ) {
     return;
  }

  // Ensuring the row number is within bounds
  if ( ! (row_num >= 0 && row_num < grid.length) ) {
    console.log ( 'bad row num!!!' );
    return;
  }

  // Calculating the target row based on direction
  // Utilizing falsy check due to direction being either 0 or 1
  if ( direction ) {
     row_num++; 
  } else {
     row_num--;
  }

  // Handling out-of-bounds scenarios by wrapping around
  if ( row_num < 0 ) {
     row_num = grid.length - 1;
  } else if ( row_num >= grid.length ) {
     row_num = 0;
  }

  // Returning the updated index 
  return row_num;
}

Usage example:

var startIndex = findRow ( 'janice' );
// Note that startIndex might be undefined if no matching row is found!
// Be sure to handle such cases.
var newIndex = navRow ( startRow, 0 ); // move back or wrap to end
var newIndex = navRow ( startRow, 1 ); // proceed forward or wrap to start

Your initial row was represented as grid[ startIndex ], while the newly navigated row is now accessed using grid[ newIndex ].

This method eliminates the need for class or global variables to track the current index during navigation. The concept of newIndex essentially becomes akin to startIndex, hinting at possible recursion or generator/yield patterns. In any case, this approach proves advantageous.

It's worth noting that the provided code assumes a very simplistic grid structure. If your grid exhibits complexity like non-unique row values, duplicates, uneven rows, etc., further refinement and testing are necessary (although the outlined code should still serve its purpose effectively). Begin by outlining the process, verifying your logic and safeguards before delving into implementation.

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 steps can I take to prevent Transform Control from displacing my object in the event of a collision, by utilizing raycasting?

Currently, I am working with Three.js and have a situation where there are cubes inside a box. The Transform Control is being used to manipulate the position of the cubes within the box using the mouse. My goal is to implement raycasting to detect collis ...

angular js: accessing nested json elements made easy

**How can I use Angular to display seeds or other data from "torrents" in HTML? ** Although this code appears to be working fine, it does not display any information when trying to show the seeds. HTML CODE <section class="list"> <article ...

Translating a few lines of JavaScript into C#

I'm looking to convert some code from JavaScript to C#, but I'm having trouble grasping a certain section... function getHisto(pixels) { var histosize = 1 << (3 * sigbits), histo = new Array(histosize), inde ...

What is the technique for performing asynchronous querying of multiple SQL databases?

Currently, I am in the process of developing a web application using nestjs and typeorm. I have been contemplating the functionality of the following code: const r1 = await this.connection.query(sqlA) const r2 = await this.connection query(sqlB) Does th ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

Unfortunately, the header and footer are not lining up correctly with the main body on our mobile site

I've been tasked with creating a fully responsive website, but I'm encountering difficulties with the mobile design. Specifically, when I switch to mobile dimensions like an iPhone 12, the header and footer don't line up properly with the ma ...

Using VB.NET to run JavaScript through Selenium's ChromeDriver

I've tried various methods in C# but I can't seem to get them working in VB.NET. It's possible that I'm not initializing it correctly. My goal is to run javascript on a loaded URL using the chromedriver. This is what my code looks like ...

Utilizing the Sheet Elite API - Step-by-Step Guide for Sending Data to a Designated Sheet Through a POST Request

Recently, I've been working on a project that involves using the Sheet Best API to submit data directly to Google Sheets. However, I'm running into an issue where the data is only being sent to the first sheet out of three. Despite having all the ...

Combining an if-statement with an HTML button within a single function in JavaScript

I'm currently developing an HTML table that includes fields that must be filled, but I want to allow one of the fields to be optional. The structure of my code is as follows: name.html ... <table> <tr> <td>Number 1:</td& ...

ways to trigger an event and pass it to a JavaScript function using a hyperlink

This specific "href="javascript:stop(this);" pattern allows the hyperlink object to be passed to the stop function. However, I also need to pass the invoked event to that function. How can I achieve this? Since my records are loaded through AJAX, I am unab ...

What is the best way to retrieve the previously chosen item from an array?

I have successfully implemented dynamic pill tabs with one minor issue remaining. The most crucial aspect is that when I remove a pill, I want it to return to the previously opened tab. I have provided a StackBlitz example without routes on this page: -> ...

I'm having trouble with my AngularJS Spinner directive

Check out this simple directive I created to display a spinner on my button while something is happening remotely: http://plnkr.co/edit/rAJ4X7A3iidmqUD2M63A?p=preview Here's the html: <!DOCTYPE html> <html ng-app="app"> <head> ...

Trying to access properties of undefined

I am having trouble adding the form control class to my select statement. The issue arises when props become undefined. Here's the code snippet: const useStyles = makeStyles({ root: { width: "100%", maxWidth: 500 } }); const cl ...

Customize RequireJS dependencies for flexible dependency injection

Currently, I am faced with integrating a component that would greatly benefit from Dependency Injection (DI) into an existing framework where DI was not considered during its initial design. The configuration defining dependencies is sourced from a backend ...

Ensuring the server application is up and running before initiating the mocha tests

This is similar to Ensuring Express App is running before each Mocha Test , but the proposed solution isn't effective + I am utilizing a websocket server In essence, I'm making use of a websocket framework called socketcluster and this represent ...

Steps to show a message on screen for a duration of 3 seconds using JavaScript

setTimeout(function(){ document.getElementById("alarmmsg").innerHTML=msg; },3000); The code above is successfully displaying the message but it's not going off the screen as expected. What might be causing this issue? ...

React 17 Form not registering the final digit during onChange event

I am currently experiencing an issue with a form that includes an input field of type "number." When I enter a value, the last number seems to be skipped. For example: If I input 99 into the box, only 9 is saved. Similarly, when typing in 2523, only 252 ...

Steps for making a webpack-bundled function accessible globally

I am currently working with a webpack-bundled TypeScript file that contains a function I need to access from the global scope. Here is an example of the code: // bundled.ts import * as Excel from 'exceljs'; import { saveAs } from 'file-save ...

Caught in the midst of a JSON update conundrum

I need some help with my JavaScript/JSON coding. I have a script that loads JSON data and displays it on an HTML page. Now, I want to know how I can update this data. Specifically, I want the script to update the location of the person when a button is cli ...

D3js stacked bar graph displaying incorrect bar placements

Currently, I am attempting to create a stacked bar chart using D3js. My main issue lies in correctly setting the y and y0 attributes to ensure that the bars are displayed in their correct positions. It seems like there might be a miscalculation somewhere, ...