samedi 2 février 2019

"Cannot read property 'formatTime' of undefined" error in array.sort() function

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.




Aucun commentaire:

Enregistrer un commentaire