[SalesForce] Lightning client side sorting (using a separate function, not inline)

I'm trying to implement a sorting function for the records returned by a callback. The normal javascript a.value - b.value inline implementation is working. This is the working code that I have:

/aura/myComponent/myComponentHelper

$A.getCallback(function(result) {
  var cases = result.values.cases;
  cases.sort(function (a, b) {
    return b.CaseNumber - a.CaseNumber
  })
})

I wanted to make a separate function out of this inline function, so I did a function like this:

/aura/myComponent/myComponentHelper

getCases : function (component) {

  var self = this;

  ... other codes...

  myPromise.then (
    $A.getCallback(function(result) {
      var cases = result.values.cases;
      cases.sort(self.sortByCaseNumber());
      ... other codes ...
    })
  )
  .catch (
    ... other codes ...
  )
},

sortByCaseNumber : function(a, b) {
  return b.CaseNumber - a.CaseNumber
}

However, I'm encountering an Error in $A.getCallback() [Cannot read property 'CaseNumber' of undefined].

Inside the sortByCaseNumber function, the values of a and b are both undefined. Not sure why this is happening. I'm checking the values of the cases list right before I sort it and the list definitely contains an array of case objects, and the CaseNumber field is there.

Best Answer

You're not supposed to call the function, but pass it in as a parameter to sort:

  cases.sort(self.sortByCaseNumber);

Note the lack of parentheses, because we're not actually calling the function, but instead passing it in as a parameter, much like you would a string or number (functions are formally of type Function, so you can use them like normal parameters). This is a pretty common idiom in JavaScript (setTimeout, setInterval, sort, map, reduce, Promise, etc) and also useful in Lightning (e.g. $A.getCallback), so you'll want to remember this.

Related Topic