"Troubleshooting JS issue: Unable to get index of element in multid

I'm currently facing an issue with trying to locate the index of a number within a 2d array. The console is throwing an error that says:

Uncaught TypeError: block[((a * 10) + c)].indexOf is not a function

I suspect the problem lies in how I am accessing the elements in the array, but unfortunately, I haven't been able to pinpoint the exact cause.

Below is the code snippet in question:

var block = [];
var temp;
var del;

for(var a = 0;a < 9;a++){
    for(var b = 0;b < 9;b++){
        temp = parseInt(prompt("enter element number " + b + " of row number " + a));
        console.log(temp);
        if(temp>0){
            block[a*10+b] = temp;
        }else{
            block[a*10+b] = [1,2,3,4,5,6,7,8,9];
        }
//      console.log(block[a*10+b]); 
    }
}
for(var a = 0;a < 9;a++){
    for(var b = 0;b < 9;b++){
        if(typeof(block[a][b]) == "number"){
            for(var c = 0;c < 9;c++){
                if(c != b){
                    del = block[a*10+c].indexOf(b);
                    block[a*10+c].splice(del,1);
                }
            }

        }

    }
}

Answer №1

The block array is a mix of data types when the user inputs values. A nested array is assigned to an element in block if the input is not numeric, indicating possible values for that cell in a Sudoku game.

In the second part of your code, it's important to differentiate between handling numeric inputs and arrays in block. Utilize Array.isArray() to determine if an element is an array before making changes.

There are some issues in the script:

  • Make sure to access elements in block correctly using block[a*10+b].
  • The usage of b in .indexOf(b) is incorrect; use block[a*10+b] instead.
  • Only execute splice() if the result of indexOf is non-negative to prevent removing elements unintentionally.

Here is a modified version of your code with improvements:

document.querySelector('button').onclick = function () {
    var block = [];
    var temp;
    var del;
    var text = document.querySelector('textarea').value.replace(/\s+/g, '');
    for(var a = 0;a < 9;a++){
        for(var b = 0;b < 9;b++){
            temp = parseInt(text[a*9+b]);
            if(temp>0){
                block[a*10+b] = temp;
            }else{
                block[a*10+b] = [1,2,3,4,5,6,7,8,9];
            }
        }
    }
    for(var a = 0;a < 9;a++){
        for(var b = 0;b < 9;b++){
            var num = block[a*10+b];
            if(typeof num == "number"){
                for(var c = 0;c < 9;c++){
                    if(c != b && Array.isArray(block[a*10+c])){
                        del = block[a*10+c].indexOf(num);
                        if (del > -1) 
                            block[a*10+c].splice(del,1);
                    }
                }
            }
        }
    }
    document.querySelector('pre').textContent = 'block='+ JSON.stringify(block);
};
<textarea rows=9>
53..7....
6..195...
.98....6.
8...6...3
4..8.3..1
7...2...6
.6....28.
...419..5
....8..79
</textarea>
<button>Process</button>
<pre></pre>

Keep in mind that null values might exist in block due to indexing logic, one index remains untouched per "row".

Answer №2

Although I haven't had a chance to review your second for loop, the concept remains similar to what I have demonstrated in the provided snippet. The key is to establish a temporary array within the outermost for loop iterating over values of a (excluding the inner nested for loop for values of b). Within the for loop for b, you should append elements into that temporary array (referred to as temp). Subsequently, before moving on to the next iteration of a, ensure you add this temporary array temp to the main block array. This methodology facilitates the creation of a 2D array.

var block = [];
var del;

for(var a = 0; a < 9; a++) {
  let temp = [];
  for(var b = 0; b < 9; b++) {
    let num = parseInt(prompt(`Enter element ${b} of row ${a}:`));
    if (num > 0) {
      temp.push(num);
    } else {
      // block[a*10+b] = [1,2,3,4,5,6,7,8,9];
      temp.push(b);
    }
  }
  block.push(temp);
}

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

Matching Parts of Strings with Regular Expressions in JavaScript

I've created an extensive regex pattern to identify URLs such as: /^\/([^\/.?]+)(?:\/([^\/.?]+)(?:\/([^\/.?]+)(?:\.([^\/.?]+))?)?)?$/ It successfully matches: /foo/bar/1.html and returns ['foo', & ...

Why Does React Material-UI Switch Styling Keep Changing Sporadically?

Currently, I am trying to integrate a switch component from MUI into my code. Strangely enough, upon the initial page load, the switch appears exactly as it should - identical to the one displayed on the MUI site. However, upon reloading the page, it under ...

Utilizing Javascript to load a vast amount of data onto the browser, followed by initiating an XML

Looking for a solution to send XML requests containing values and content from files obtained by filling out an HTML form. With 5 large files, some exceeding 70 MB, I have implemented JavaScript functions to load file contents and assemble the XML request. ...

Discovering, storing, and displaying JSON data in JavaScript

I am currently working on a PHP file called rows2.php that displays results from a database by showing the new id of the field in this format: {'new_id':'92'} My goal is to use JavaScript to load this data and add the new_id surrounded ...

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

"An easy way to dynamically update a select dropdown based on the data of the corresponding row in a table using jQuery

Having some trouble with dynamically populating form input fields in a table. The first row works fine, but when I change the select option in the second row, it affects the previous field instead of the current row: How can I ensure that changing the sel ...

Retrieve the earliest and latest dates from a JSON file to utilize with FlatPicker

I have a file in an unknown format, possibly JSON, with dates listed. I am attempting to extract the minimum and maximum dates from this data in MM/DD/YYYY format for use as variables in Flatpicker's minDate and maxDate options. The current AJAX call ...

Mastering the art of transitioning between DIV elements

I am looking to implement a rotating three-card display on click, and have come up with the following code: $('.box1').click(function(){ $('.box1').toggleClass('removeanimate'); $(this).toggleClass('go'); ...

Graph not displaying dates on the x-axis in flot chart

I've been attempting to plot the x-axis in a Flot chart with dates. I've tried configuring the x-axis and using JavaScript EPOCH, but have had no success so far. Here's a snippet of my code: <?php foreach($data[0] as $i => $d){ ...

Verify image loading using jQuery

<img src="newimage.jpg" alt="thumbnail" /> I am dynamically updating the src attribute of this image. Is there a way to verify if the image has been successfully loaded and take action once it is? Appreciate any guidance on this matter. ...

What is the best way to apply CSS modifications to sibling elements that are related?

I have several parent div elements with pairs of button and div child elements. My goal is to apply changes to the corresponding div when a button is clicked. For example, clicking Button 2 should only affect toast 2. However, I am facing an issue where o ...

Is there a Facebook application embedded in the user's wall?

Is it feasible to create a website similar to YouTube, where users can share it on Facebook and run the app (in this case, the video player) directly on their wall without having to visit the YouTube page? If it is possible, is this functionality limited ...

Determine the specific table entry that was clicked on

Currently, I am working on developing a dynamic table that includes a button in one of its columns, which triggers a bootstrap modal. I'm a bit unsure on how to determine which button was clicked and how to populate the table accordingly. Admittedly, ...

What is the best way to display an error message when a necessary field is left empty?

I am currently utilizing a plugin to validate my form. My goal is to display an error message on the button when clicked, as all fields in my form are required and need validation. Despite attempting the code below, it hasn't been successful: <Fo ...

When I upgraded my "react-router-dom" from version "5.2.0" to "6.14.0", I encountered a warning stating "No routes matched location"

After updating react-router-dom from version "5.2.0" to "6.14.0", I encountered a warning saying "No routes matched location." Initially, I received an error stating that "<Route> is only meant to be used as a child of <Routes>, not rendered d ...

After a successful transactWrite operation using DynamoDB.DocumentClient, the ItemCollectionMetrics remains unpopulated

Currently, I am utilizing a transactWrite instruction to interact with DynamoDb and I am expecting to receive the ItemCollectionMetrics. Even though changes have been made on the DynamoDb tables, the returned object is empty with {}. Does anyone have any ...

Implementing RXJS subscription using a Subject object

What is the benefit of using "Subscribe providing subject" and what does this entail: 1- The purpose of using subscribe providing subject import { Subject, from } from 'rxjs'; const newSubject = new Subject<number>(); newSubject.subscr ...

What could be causing this error I'm receiving: instance versus prototype difference?

Can someone help me understand the difference between .prototype and regular instances in JavaScript? I am confused about why this code is not working and getting a type error: "undefined is not a function". I am experimenting with the Ninja() class and ...

Setting the texture for a loaded glb model using Three.js

After successfully loading a basic glb model created in SketchUp using Three.JS, I encountered an issue with displaying text on the model. The model includes a group identified as Text. Despite being able to load and visualize the model correctly in Three ...

Dynamic Bootstrap tooltip

I have a simple Javascript code snippet that I'm struggling with: $("#myinput").hover(function(){ if(condition){ $(this).tooltip({placement: "bottom", title: "mytitle"}); } ); Accompanied by its HTML cou ...