What is the issue with this bubblesort algorithm that is preventing it from

In my current coding situation, I am trying to organize an array based on the second element of each contained tuple. The process appears to be running smoothly until it reaches the last element. At that point, an exception is thrown.

ERROR TypeError: Cannot read property '1' of undefined

Below is the code I have been using:

public list:Array<[string, number]> = new Array<[string, number]>();
//{["A", 0],["B", 8], ...}
...

var sorted = false
while (!sorted){
    sorted = true;
    this.list.forEach(function (element, index, array){
      alert(element);
      if (element[1] > array[index+1][1] ) {
        array[index][1] = array[index+1][1];
        array[index+1] = element;
        sorted = false;
      }
   });
}

I'm struggling to understand why this particular code isn't producing the desired results.

Answer №1

This example illustrates a common error:

  array[index+1][1];

This results in the following error message:

ERROR TypeError: Cannot read property '1' of undefined

The reason for this error is that when the iteration reaches the last index, e.g., 5, it attempts to access 6 from the array, which does not exist. To avoid this issue, it's necessary to skip the last index while iterating, as shown below:

 if(array.length - 1 === index)
  return;

One way to address this problem is through the following approach:

 var sorted = false;

 while(!sorted){
   sorted = true;
   for(let index = 1; index < array.length; index++) {
      if(array[index][1] < array[index - 1][1]) {
       ([array[index], array[index - 1]] = [array[index - 1], array[index]]);
       sorted = false;
   }
 }

An alternative, simpler solution can be achieved with:

 array.sort((a, b) => a[1] - b[1])

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 div is populated after the onload event is finished

Currently, my onload event is functioning correctly. However, I am encountering an issue where the second part of the onload event calls another function before the first part is finished. The initial part inserts information into an input field, while th ...

Using Promise.all to loop through generators is not a supported operation

Exploring the world of Javascript generators and promises, it becomes clear that they work well together. To effectively navigate through a coroutine of promises using Promise.coroutine from the Bluebird library simplifies executing promises in the correct ...

Unsuccessful attempts to animate with Jquery in Google Chrome are persisting

I've been facing a challenge with my jquery code that seems to be getting the "click" function but does not animate. Instead, it just abruptly jumps without any smooth animation. I've spent hours trying to troubleshoot this issue. Here is the Jq ...

The setInterval function with a time interval set to 1ms does not appear to function exactly as a 1ms delay

I'm attempting to measure the duration of a file download using an HTTPRequest as seen below: function getFile() { 'use strict'; var url = "data.bin"; var rawFile = new XMLHttpRequest(); var timer_var = setInterval( theTimer ...

What should I do when the ng-click event doesn't open a new window

<p ng-click='window.location.href="{{data.url}}"''>{{data.name}}</p> Is there anything incorrect about this code snippet? I attempted using onclick as well, but encountered an error in the console. ...

Do not store start_url in the service worker cache

I'm facing some challenges while trying to set up a service worker for my website. My goal is to only cache css/js/fonts and specific images/svg files, without caching the HTML since it's constantly being updated every minute. Although it seems ...

Remove numerous lines from the text box

I have a textarea and I need to remove several lines when the user presses the button. For example: The current content in the text area is as follows; Australia - Mobile Optus Australia - Mobile Telstra Australia - Mobile Vodafone Australia - Special A ...

Problem with redirecting when using HTTPS

I recently implemented an SSL Certificate and made changes to the web.config file. Here is the updated code: <system.webServer> <rewrite> <rules> <rule name="removed by me" stopProcessing="true"> ...

Error: Attempting to access property '7' of an undefined value

I am currently working on a code that checks if the checkboxes for CEO_box and Acc_box are checked. If they are, an email is sent to the corresponding email address in the column, and the inform_cell is set as 'informed'. However, I keep encounte ...

Error with Angular Universal SSR CSS animation transformation

I recently implemented Angular universal into my application by following the step-by-step guide provided at https://angular.io/guide/universal. While the process itself was straightforward, I am currently facing a challenge with the following error: ERRO ...

Combining an anchor tag in HTML with PHP

I have attempted: <?php include("delete.php") ?> <?php .... .... .... if($result=mysql_query($sql)) { echo "<table><th>Id</th><th>Name</th><th>Description</th ...

React event handler not activating on click

Being new to React, I am facing an issue with getting the onclick event to work. The problem arises when the alert is not firing up as expected. class Application extends React.Component{ render () { return ( <div> ...

I'm looking for ways to decrease the size of my Expo build for iOS, which currently sits at approximately 188

After executing the expo build: ios command, I noticed that the generated IPA file is much larger than expected at around 188MB. This seems unusual considering the app has only a few pages with listViews. Any ideas on why the size is so large for iOS whe ...

The function getattribute() on the edge is malfunctioning and returning a null value

Has anyone encountered issues with the getAttribute() function while creating an extension for Edge? I am currently facing a problem where it is not returning the attributes of the element that I am searching for. This is what my code looks like on Edge a ...

What are some effective ways to analyze jQuery and JavaScript using web development tools?

I'm struggling to use web development tools to inspect the JavaScript on websites. It's challenging to identify which parts of a site are utilizing JS, unlike CSS or HTML where it's more visibly defined. Even when I attempt to delete some J ...

FlexSlider in WordPress is failing to display captions

Before pointing out any similar questions, please note that the answer from those sources does not apply to my specific code. I am trying to achieve this through a function as outlined here But I am struggling to figure out how to add captions only if th ...

Restrict the option to schedule an event to only a designated month on fullcalendar

Here's a query related to fullcalendar: Is there a way to restrict users from saving events in certain months while allowing them to view those months? I want to make specific months read-only. Any guidance on how to achieve this would be appreciated ...

Meshes that overlap with transparency features

Could anyone help me with this issue I'm facing? I have a scenario where I am rendering multiple meshes in Three.JS with different solid colors and transparency. However, these meshes are overlapping and the colors are blending together in the overlap ...

Efficiently Managing Forms with SharePoint Online

Recently, I created a basic HTML/PHP form that collects input data and generates a company-approved email signature in HTML format. The form simply captures the information entered by users and displays it in the signature layout. Check out the form below ...

What is the best way to eliminate an object from an array by using Lodash?

Seeking assistance in removing an object from an array using Lodash. Within server.js (utilizing NodeJS): var lodash = require('lodash')(); var rooms = [ { channel: 'room-a', name: 'test' }, { channel: & ...