Retrieving row and column values from an 81-element indexed array

I am working with an indexed JavaScript array that contains exactly 81 elements. These elements will form a 9x9 grid, similar to a Sudoku puzzle. Right now, I am trying to figure out the most efficient way to extract row and column values from this array.

For instance, the function getRow(2) should return an indexed array of 9 values, representing the second row of the 81-element array. Similarly, the getColumn(2) function should work in a similar manner for columns.

Currently, my getRow() function looks like this:

function getRow(rowId){

    // Indexes for each row in the 81-element array
    var rowIndexes = {
        1: [0,1,2,3,4,5,6,7,8],
        2: [9,10,11,12,13,14,15,16,17],
        3: [18,19,20,21,22,23,24,25,26],
        4: [27,28,29,30,31,32,33,34,35],
        5: [36,37,38,39,40,41,42,43,44],
        6: [45,46,47,48,49,50,51,52,53],
        7: [54,55,56,57,58,59,60,61,62],
        8: [63,64,65,66,67,68,69,70,71],
        9: [72,73,74,75,76,77,78,79,80]
    };

    // New array to store row values
    var rowValues = new Array();

    for(var i=0; i < 9; i++){
        // Extracting row values from the 81-element array
        rowValues.push(GRID_ARRAY[rowIndexes[rowId][i]]);
    }

    return rowValues;

}

Is there a more dynamic and optimal method to calculate both row and column values based on the specified row/column ID?

Thank you!

Answer №1

If row and column fall within the range of 0 to 8, you have the ability to determine the index by using this specific formula:

index = row * 9 + column

Answer №2

To achieve the same outcome for the function getColumn(colId), follow this code snippet:

for(let i = 0; i < 9; i++){
    // Retrieve column value from an 81-element array
    columnValues.push(GRID_ARRAY[rowIndexes[i][colId]]);
}
return columnValues;

Answer №3

Thank you for your assistance! After some consideration, here is the final solution I came up with:

function extractRow(row){

    var rowValues = [];

    for(var i = 9 * (row - 1); i < 9*row; i++){
        rowValues.push(BOARD[i]);
    }

    return rowValues;

}


function extractColumn(column){

    var columnValues = [];

    for(var i = 0; i < 9; i++){
        columnValues.push(BOARD[i * 9 + (column - 1)]);
    }

    return columnValues;

}

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

The implicit wait feature in WebDriver JavaScript seems to be ineffective

Waiting for the error message to appear seems to be a bit tricky. I tried using browser.driver.manage().timeouts().implicitlyWait() but had to resort to using browser.driver.sleep() instead. this.getErrorMessage = function () { var defer = protracto ...

Exploring the Differences in Hash Arrays within Ruby

Exploring the differences between two complex nested hashes with multiple hash arrays within arrays is proving challenging. Is there a preferred method for performing this comparison? It seems that there are no pre-existing libraries or functions that are ...

Iterate through an array of strings within a paragraph tag

In my current situation, I am dealing with an array of strings and would like to iterate through it within a <p> tag if the array is empty. This is what I have so far: <p *ngIf="detailMessageMultilines">{{detailMessageMultilines}}< ...

Raycast in Three.js is struggling to locate object

Whenever I select a 3D model, my goal is to retrieve the object's ID, name, or the actual object itself in order to effectively delete it. function onDocumentMouseDown( event ) { if (enableRaycasting){ event.preventDefault(); mouse.set( ( event.c ...

Converting a Curl command to a JavaScript POST request: best practices

Is it possible to convert the given curl code into a JavaScript post request that will function effectively in all browsers? curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \ -d code="{AUTHORIZATIO ...

Issue with Vue JS component on blade template page

Having trouble loading a Vue component into a Laravel blade file? Despite making changes, the content of my vue file isn't showing up in the blade file - even though there are no errors in the console. Any suggestions on how to resolve this issue woul ...

The attribute "value" for Material-UI autocomplete cannot be used in conjunction with the "getOptionLabel" attribute

<Autocomplete id="license-select" options={licReqList} value = {licReqList[0] ? licReqList[0].licReqStr : null} getOptionLabel={(option) => option.licReqStr} onChange={ha ...

Has the Angular 2 community established a standardized ecosystem?

As a developer specializing in Angular 1, I am now eager to dive into the world of Angular 2. However, navigating through the changes and rewrites can feel like traversing a confusing maze. All of the comprehensive guides I have come across date back to l ...

Retrieving JSON formatted data from PHP using jQuery

If I use a $.post method in jQuery, how can I retrieve the response from PHP? $.post("sql/customer_save.php",{ what: "edit",customer_no: $customer_no}); I want PHP to send back a response. echo json_encode(array("customer_id"=>$customer_id,"customer_ ...

Remove any duplicate words from the array and then randomize and restrict the size of the array

When creating a tag cloud from article subject titles, the process involves taking each title, splitting it into words, and storing them in an array. This array is then checked for word length greater than 3 and not included in the excluded words list. Ho ...

AngularFire - Structuring item references for child templates using ng-repeat

I have been struggling with this issue for hours and can't seem to find a solution. In my dashboard, all data from my Firebase database is visible using Ng-repeat. However, I am trying to select a specific item and view its details on another page. H ...

Is it possible to extract the image name from AngularJS and then integrate it into a Laravel blade template?

I encountered a challenge when trying to integrate Laravel blade with AngularJS. Both frameworks use the same markup for displaying variables, so I modified the AngularJS variable like this: $interpolateProvider.startSymbol('<%'); $ ...

Stop capturing mouse and keyboard events within a specific div element on all web browsers

I manage a website with forms that have jquery autosave features and are updated using ajax. These forms include various types of input elements such as textboxes, jQuery UI datepickers, and time pickers... <div id="content"> <form id="line1"&g ...

Adjusting a data point as v-model is updated

I'm working on a text input that is using the v-model to bind its value to data. I also need to trigger my parse() function whenever the value of this v-model changes, so that I can update an array within the data object. <div id="app"> < ...

Encountering an unusual error while utilizing the Rails 3 form_for with the :remote option set to true

Encountering an error and seeking assistance: try { Element.update("status", "There seems to be an issue with this product."); } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.update(\"status\", &bsol ...

Ajax: The response from xmlhttp.responseText is displaying the entire inner HTML rather than the specified text needed

This is my Ajax function. It is functioning correctly, however after the function is called, it returns a response containing HTML tags and required text. Response in value variable " <br/> <font size='1'> <table class='x ...

How can I incorporate multiple JSX files into plain HTML without using npm?

I have a question regarding importing JSX files in an HTML file without using npm and directly running it with LiveServer. I have two files, index.js and app.jsx, that I want to connect within my index.html script. How can I achieve this? Code: index.html ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

what is the method for retrieving JavaScript variables within a PHP script?

Is there a way to store a JavaScript variable value, such as var a, within a PHP script variable without relying on the post/get method or Ajax? <script> var count=3; $("#add_driver").click(function () { $( "#add_driver_section").replaceWit ...

Issue with Custom Tooltip in Mootools 1.2 - Images displaying prematurely before hover action

Encountering an issue with Mootools 1.2 Tips (custom tooltips) We are currently utilizing Joomla with the latest update that includes Mootools 1.2, and I am working with the following JS code: $$('.tipz').each(function(element,index) { ...