1

I have an array.sort() function that sorts times, however, it keeps returning this error. Here is my code:

  sortTime(columnIndex, sortingAZ){
  var rowArray = this.get('tableArr').slice(0); //gets array of arrays
    rowArray.sort(function(a,b) {
        var time1 = this.formatTime(a[columnIndex]); //formats time into military time
        var time2 = this.formatTime(b[columnIndex]);
        return time1 - time2;
        });

and here is the formatTime function that is called:

   formatTime(time){

//seperates time into hours and minutes
var colonIndex = time.search(":");
var hour = parseInt(time.substring(0, colonIndex));
var minute = time.substring(colonIndex+1, time.length);
if(time.search("pm")>=0&&hour!=12){ //if it is pm, add 12 to convert to military time (except 12 pm)
    hour+=12;
}
else if(time.search("am")>=0&&hour==12){ //if it is 12 am, set hour to 0
hour = 0;
}
var milTime = hour.toString()+minute.toString(); //recombine hour and minute
milTime = parseInt(milTime);
return milTime;
}

I have tested the formatTime() function by calling console.log(formatTime(rowArray[0][columnIndex])), and it executes correctly, no error. The error seems to be local to the rowArray.sort() function.

Also, I am relatively new here, so let me know if you need any more information or if there is something wrong with my post.

EDIT: This is different from How to access the correct `this` inside a callback? because my solution only required an arrow function. I do appreciate the in-depth explanation of this though

Alex Reed
  • 99
  • 1
  • 2
  • 11
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – adiga Feb 02 '19 at 19:49
  • Use an arrow function `rowArray.sort((a,b) => {})` – adiga Feb 02 '19 at 19:49

2 Answers2

1

Change it to arrow function so that this context will be available inside. In regular function you will not access to this until and unless you refer this to a local variable or change it to arrow function like below

   rowArray.sort((a,b) => {
    var time1 = this.formatTime(a[columnIndex]); //formats time into military time
    var time2 = this.formatTime(b[columnIndex]);
    return time1 - time2;
    });
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
0

this is undefined in the compareFunction. try:

sortTime(columnIndex, sortingAZ){
  var rowArray = this.get('tableArr').slice(0); //gets array of arrays
var that = this;
    rowArray.sort(function(a,b) {
        var time1 = that.formatTime(a[columnIndex]); //formats time into military time
        var time2 = that.formatTime(b[columnIndex]);
        return time1 - time2;
        });