SuiteScript 2.0 – “An unexpected SuiteScript error has occurred” with Array.sort()

Here is another coding challenge that set me back more time than I would have liked. Passing an array of objects to the Array.sort() function worked most of the time, but not always. And when it blew up, the error was completely unhelpful.

Please note this is server-side code. Client-side code runs in a different JavaScript engine. In my case it was running inside a Suitelet written in SuiteScript 2.0. I did NOT try this same problem in SuiteScript 2.1 which gets a completely new JavaScript engine and ES6. Perhaps it might have worked. Moving from 2.0 to 2.1 requires also updating libraries. That was too much work. Here was my basic problem:

var transactions = [
   {
      salesrep: salesrep_id,
      salesorder_total: salesorder_total
   },...
   /* In my case, there were less than 200 
      records in this array when it failed.
      This was far short of the number of 
      records it processed successfully.
      The only thing I noticed about this 
      particular set of records which caused 
      the failure was the number of records 
      where salesorder_total was zero. 
      Not all, but more than a few! */
]

var sortedbyTotalDescending = transactions.sort(
      function(a, b) {
            return a.salesorder_total <= b.salesorder_total ? 1 : -1;
      }
);

This worked correctly for months. However, there were certain times when it blew up. This is what solved the problem. And don’t ask me why. I’m clueless. It should have. Please direct your questions to NetSuite. I believe it is a bug in their SuiteScipt 2.0 JavaScript engine!

/* This one works! */
var sortedbyTotalDescending = transactions.sort(
      function(a, b) {
            if (a.salesorder_total == b.salesorder_total) return 0;
            return a.salesorder_total < b.salesorder_total ? 1 : -1;
      }
);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s