Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I can't access the array.

Uncaught TypeError: Cannot read property '1' of undefined

var n = new Date(this[Y + 1][1]).getTime();


(4) [Array(2), Array(2), Array(2), Array(2)]
   0: Array(2)
      0: "Consectetur Adipiscing"
      1: "Aug 15, 2020 15:20:10"
      length: 2
__proto__: Array(0)
1: Array(2)
      0: "Hendrerit Sit Amet"
      1: "Sep 10, 2021 18:30:15"
      length: 2
__proto__: Array(0)
2: Array(2)
      0: "Donec Congue Fringilla"
      1: "Jul 30, 2021 15:50:30"
      length: 2
__proto__: Array(0)
3: Array(2)
      0: "Nulla Vel Aliquam Odio"
      1: "Dec 25, 2021 12:10:45"
      length: 2
__proto__: Array(0)
      length: 4
__proto__: Array(0)


What I have tried:

<pre lang="JS"><pre>Object.defineProperty(Array.prototype, "bubbleSort", {
    value: function bubbleSort(){
        var Length = this.length;

        for (X = 0; X < Length; X++)
        {
            for (Y = 0; Y < Length - X; Y++)
            {
                var p = new Date(this[Y][1]).getTime();
                var n = new Date(this[Y + 1][1]).getTime();

                if (p > n)
                {
                    var Temporary = this[Y][1];
                    this[Y][1] = this[Y + 1][1];
                    this[Y + 1][1] = Temporary;
                }
            }
        }
    }
});
Posted
Updated 18-Apr-21 23:30pm

1 solution

Consider the last two iterations of your inner loop on the first iteration of the outer loop:
X === 0
  • On the penultimate iteration, Y === Length - 1; therefore, this[Y + 1] is equivalent to this[Length], which is beyond the end of the array.
     
  • On the final iteration, Y === Length; therefore, this[Y] will not return anything, because the index is beyond the end of the array.
    (this[Y + 1] will not return anything either.)

You need to fix your code to implement the sort correctly.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900