Issue with undefined arrays in the Angular merge sort visualization tool

I am currently working on developing a visualizer for sorting algorithms using Angular. However, I have encountered some difficulties while implementing merge sort. As a Java programmer, I suspect that there may be an issue with my TypeScript code and the recursive calls. Upon running the program, I keep getting errors stating 'cannot read property length of undefined'. I am feeling perplexed and struggling to pinpoint where exactly I am making a mistake.

In my initial function, I consistently divide the global array called visualArr, which is predetermined by the user and utilized for visualization purposes in my program. The subsequent function focuses on merging the divided arrays.

  performMergeSort(arr) {
    if (arr.length <= 1) {
      return arr;
    }

    const middle = Math.floor(arr.length / 2);

    let left = arr.slice(0, middle);
    let right = arr.slice(middle, arr.length);

    left = this.performMergeSort(left);
    right = this.performMergeSort(right);

    return this.performMerge(left, right);
  }

The timer function within the second code snippet plays a significant role in providing real-time visuals during the sorting process. Nonetheless, I have a hunch that there might be a flaw either in my approach or in the TypeScript implementation. Any insights or feedback would be greatly valued.

performMerge(leftArr, rightArr) {
    let lIdx = 0;
    let rIdx = 0;
    let i = 0;

    timer(0, 100)
    .pipe(takeWhile(() => leftArr.length > lIdx && rightArr.length > rIdx))
    .subscribe(() => {
      const lItem = leftArr[lIdx];
      const rItem = rightArr[rIdx];

      if (lItem > rItem) {
        this.visualArr[i] = rItem;
        rIdx++;
      } else {
        this.visualArr[i] = lItem;
        lIdx++;
      }
      i++;
    });

    timer(0, 100)
    .pipe(takeWhile(() => leftArr.length > lIdx ))
    .subscribe(() => {
      this.visualArr[lIdx] = leftArr[lIdx++];
    });

    timer(0, 100)
    .pipe(takeWhile(() => rightArr.length > rIdx ))
    .subscribe(() => {
      this.visualArr[rIdx] = rightArr[rIdx++];
    });
  }

Answer №1

An issue like this typically arises when the array is not initialized properly. Here's a suggestion to fix it:

newArray:number[]=[];

Answer №2

A common issue is trying to access the length property of an array before it has been defined or initialized. To avoid this, always make sure to initialize your arrays properly:

If you know the type: myArray: string[] = []

If not, simply use: myArray = []

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

Transform the IO type to an array of Either in functional programming with the fp-ts

Looking for assistance with implementing this in fp-ts. Can someone provide guidance? const $ = cheerio.load('some text'); const tests = $('table tr').get() .map(row => $(row).find('a')) .map(link => link.attr(&apos ...

How can I retrieve properties from a superclass in Typescript/Phaser?

Within my parent class, I have inherited from Phaser.GameObjects.Container. This parent class contains a property called InformationPanel which is of a custom class. The container also has multiple children of type Container. I am attempting to access the ...

Utilizing TypeScript to perform typing operations on subsets of unions

A TypeScript library is being developed by me for algebraic data types (or other names they may go by), and I am facing challenges with the more complex typing aspects. The functionality of the algebraic data types is as follows: // Creating ADT instatiat ...

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...

Connecting HTML to an AngularFirestore collection using snapshotChanges

In my mobile app, I am using AngularFirestore2v5/rxjs to connect a hybrid Ionicv3/Angularv4 app to a Firestore collection. While binding UI with AngularFirestore.valueChanges works fine, switching to snapshotChanges for retrieving the id is causing some is ...

Looking to retrieve the smallest amount of array sets in Angular4

I'm currently developing an Angular 4 application and facing an issue with a function I'm trying to write. The goal is to extract the minimum and maximum numbers from three array objects. The yAxisData object consists of three yaxis array objects ...

What could be the reason for the tsc command not displaying compilation errors when compiling a particular file?

My file, titled app.ts, contains the following code snippet: interface Foo { bar:String; } const fn = (foo? :Foo) => foo.bar; When I run tsc from the root folder with strict:true in my tsconfig.json file, I receive an error message like this ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

What could be causing the import alias issue in the latest version of Next.js, version 12

Below are my CompileOptions: { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": false, "skipLibCheck": tr ...

Comprehending the concept of TypeScript type assertion

Currently, I'm learning TypeScript and I came across a code snippet that is causing some confusion. var str = '1' var str2:number = <number> <any> str //str is now of type number console.log(typeof(str2)) log: String From m ...

Struggling to figure out how to change the display when navigating between different routes

I've been struggling for the past 3 hours trying to switch between routes. Let me explain further: Server Template HTML: <!-- I want the first div to display when the component opens, but disappear and show router-outlet when a button is clicked. ...

Angular 2 and .NET Core 2.0 triggering an endless loop upon page refresh detection

My application, built with dotnet core 2.0 and angular 2, allows me to view member details. The process begins with a list page displaying all the members from a SQL Server database. Each member on the list has a link that leads to an individual details pa ...

What is the method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

Guide on integrating an element into a different element in a Vue 3 Tree Viewer

In my current setup, I've implemented a TreeView component that holds a tree. Each tree entry includes Children with their own unique label, perm, and further children. Take a look at an example of the tree: App.vue let tree = ref({ label: 'o ...

The data type 'boolean' cannot be assigned to the type 'CaseReducer<ReportedCasesState, { payload: any; type: string; }>'

I recently developed a deletion reducer using reduxjs/toolkit: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk } from "../store"; import { ReportedCase, deleteReportCase } from "../../api/reportedCasesApi"; import history ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Bundle Angular library exports along with its corresponding models

I am in the process of developing an angular library for our company's private npm repository. Within this library, I aim to export classes that are utilized (injected via @Input()) in the library components. Here is a sample model: export class AdsT ...

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

Enhancing a UMD module definition with TypeScript 2: A step-by-step guide

Currently, I am in the process of creating TypeScript definition files for two libraries that are meant to be used with the new @types approach. Both libraries adhere to the UMD pattern, allowing them to be consumed either as modules or by referencing them ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...