Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeating numbers within a row, column, or 3x3 sector - I thought of organizing the points into three identical lists of 81, but in three different ways: by column, row, and sector.

Therefore, I need an Array that consists of three Arrays, each containing nine Arrays of nine points.

Even though I know that Array<Array<Point>> has a length of 9, and I have declared it as such, when I log it to the console, it appears to have a length of 9. My assumption was that there are nine null Array<Point> within. I attempted to push points into any of those 9 Arrays, but I faced difficulties as I kept receiving an error stating that grid[0][x] is undefined. Any suggestions or ideas would be greatly appreciated. Thank you.

  gridByX:Array<Array<Point>> = new Array<Array<Point>>(9);
  gridByY:Array<Array<Point>> = new Array<Array<Point>>(9);
  gridByS:Array<Array<Point>> = new Array<Array<Point>>(9);
  grid:Array<Array<Array<Point>>> = [this.gridByX, this.gridByY, this.gridByS];

  constructor() {}

  ngOnInit() {
    this.populateGrid();
  }

  populateGrid(){
    let counter = 0;
    for (let x = 0; x < 9; x++){
      for (let y = 0; y < 9; y++){
        let point = new Point(counter, x, y);
        this.grid[0][x].push(point);
        this.grid[1][y].push(point);
        this.grid[2][point.sector].push(point);


      }
    }
  }

Answer №1

 xGrid:Array<Array<Point>> = new Array<Array<Point>>(9);
  yGrid:Array<Array<Point>> = new Array<Array<Point>>(9);
  sGrid:Array<Array<Point>> = new Array<Array<Point>>(9);
  grid:Array<Array<Array<Point>>> = [this.xGrid, this.yGrid, this.sGrid];

  constructor() {}

  ngOnInit() {
    this.initializeGrid();
  }

  initializeGrid(){
    let counter = 0;
    for (let x = 0; x < 9; x++){
      for (let y = 0; y < 9; y++){
        let point = new Point(counter, x, y);

        grid[0][x] = grid[0][x] || [];
        grid[0][x].push(point);

        grid[1][y] = grid[1][y] || [];
        grid[1][y].push(point);

        grid[2][point.sector] = grid[2][point.sector] || [];
        grid[2][point.sector].push(point);
      }
    }
  }

Make sure to declare the index property before trying to manipulate it.

Answer №2

When it comes to using this outside of an instance scope, it's important to note that the line:

grid:Array<Array<Array<Point>>> = [this.gridByX, this.gridByY, this.gridByS];
should not be set as a class property

Simply keep

grid:Array<Array<Array<Point>>>;
for property declaration and perform the assignment within the constructor() {} method

Answer №3

After some consideration, I realized that there are actually 9 null Array<Point> elements present.

While it is true that there are null arrays, they are not the same as empty arrays. To be able to add elements to them, you need to instantiate them with an actual array object first.

Here's a concise three-line solution to create these arrays:

gridByX:Array<Array<Point>> = new Array<Array<Point>>(9).fill().map(() => []);
gridByY:Array<Array<Point>> = new Array<Array<Point>>(9).fill().map(() => []);
gridByS:Array<Array<Point>> = new Array<Array<Point>>(9).fill().map(() => []);

Using fill without arguments initializes the arrays with 9 undefined values, which are then replaced with empty arrays.

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 sets template-driven and reactive forms apart in practice?

Exploring the Angular2 new Forms API has revealed two distinct approaches to forms: Template driven and reactive (model-driven) forms. I am curious about the real-world differences between these two methods, beyond just syntax. Which approach is more adva ...

Issues with parsing Json data

Here is a JSON file: { "noticiaDTOs": [ { "idiomaPais": { "idioma": { "id": 3, "iso6391": "pt" }, "pais": { "id&quo ...

Ways to switch out the background image using jQuery

I am currently using jQuery to dynamically change the background image of a web page. Right now, I have implemented two separate buttons that toggle between Image A and Image B. By default, Image A is displayed on the page. My goal is to enhance this func ...

I am looking to incorporate a new "ID" column into my mui data grid table in ReactJS that will incrementally count from 0 to the total number of rows

When displaying data from an API in a datagrid table component with multiple columns, it is necessary to include a column for the ID which should have values ranging from 0 to the number of rows. Currently, the Object_id is being displayed in this cell. T ...

Attempting to utilize pdf.js may result in an error specifying that pdf.getPage is not a recognized function

After installing pdfjs-dist, I attempted to extract all text from a specific PDF file using Node and pdfjs. Here is the code I used: import pdfjs from 'pdfjs-dist/build/pdf.js'; import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry.js&a ...

Script to pop up cancel alert box

There's a dilemma with this code - if you click CANCEL the first time the box pops up, it continues to run. I'm unsure of how to make it redirect to the underlying page when clicked on cancel for the first time. var numero= prompt ("Enter a nu ...

Implementing real-time search functionality using API calls in Angular

Seeking guidance on implementing Typeahead for a global search feature in my app. When users type, it should call an API and display results in a drop-down menu. I am a beginner in Angular and Typescript, so any working examples with code would be greatly ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

Creating a personalized installation pathway for NPM, Angular, and TypeScript on Windows operating systems

Is there a way to prevent NPM and Angular from using the folder C:\Users\XXXXXX\AppData\Roaming\npm in Windows? I am trying to globally install Node.Js and Angular on a different disk (using the command NPM i --prefix D:\MyF ...

Filtering and selecting tables in HTML

I am dealing with an HTML table that combines static data and MySQL input. The filtering functionality is working properly, but I am struggling to add the options "yes" and "no" to the selection list. These values are test inputs fetched from MySQL. I need ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

Why have the bars been positioned on the left instead of the right, and why does the mobile version require sliding instead of simply accessing the menu through a function?

Hello everyone, I'm currently working on designing a mobile-friendly header menu with the bars positioned on the right side of the screen. The goal is to utilize JavaScript to allow users to click either an 'X' icon or the bars to open the m ...

Converting a JavaScript variable into an xls or csv file

My application currently uses Javascript for calculations and data plotting, but I want to give users the ability to download the data as a csv or xls file. Is there a way in Javascript or another method where users can click a button, enter a filename, an ...

Exploring the possibility of integrating direct search functionality into the URL bar within an Angular application

One interesting feature I observed on GitHub is that after typing "github.com" in the URL bar, you can directly search by pressing the spacebar, which activates the "search mode." Here's how it looks like on Chrome: https://i.sstatic.net/XIgJu.png I ...

Show only specific data from JSON results

I am trying to display a specific cryptocurrency's price without the need for curly braces or explicitly stating "USD". Currently, it appears as {"USD":0.4823} when using the following code: <script> $(document).ready(function () { ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

JavaScript - the global and local variable dilemma

REVISED2: I'm encountering an issue with converting images to canvas using Pixastic in HTML5. How can I 'return' this converted image back to a global variable? Any suggestions? <img id="mainIllustration" alt="main illustration" src="Img ...

Reposition HTML elements using JavaScript

Is there a way to use JavaScript or jQuery to replace the image with class "fnone" located under the span element with class "ddlabel"? <span id="flat_title" class="ddTitleText "> <img class="fnone" src="images/pinc.png"> <span ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

What is the best method for transforming a stream into a file with AngularJS?

Currently, I have a server returning a file stream (StreamingOutput). My goal is to convert this file stream into an actual file using AngularJS, javascript, JQuery, or any other relevant libraries. I am looking to display the file in a <div> or ano ...