1

While implementing JS resolvers in AWS AppSync, I can't find a way to sort an Array of objects.

The documentation of AppSync (https://docs.aws.amazon.com/appsync/latest/devguide/built-in-objects-functions.html) mentions that Array.prototype.sort() is supported, and indeed if I pass a simple array (of Strings, for example), it is working OK. However, for objects, I can't get it to work.

Trying an inline arrow function:

array_of_objects.sort((a, b) => (a.event_ts - b.event_ts))

fails with

"errorType": "UNSUPPORTED_SYNTAX_TYPE",
"value": "Unsupported Syntax Type: ArrowFunction"

Trying an external arrow function:

const compareFn = (a, b) => {
        return (a.event_ts - b.event_ts)
        if ( a.event_ts < b.event_ts ){
            return -1;
          }
          if ( a.event_ts > b.event_ts ){
            return 1;
          }
          return 0;
    };

array_of_objects.sort(compareFn)

It doesn't sort the array in place or return a sorted array.

Trying a function argument:

const compareFn = function(a, b) {
        return (a.event_ts - b.event_ts)
        if ( a.event_ts < b.event_ts ){
            return -1;
          }
          if ( a.event_ts > b.event_ts ){
            return 1;
          }
          return 0;
    };

array_of_objects.sort(compareFn)

Fails with:

"errorType": "UNSUPPORTED_SYNTAX_TYPE"
"value": "Unsupported Syntax Type: FunctionExpression"
Guy
  • 12,388
  • 3
  • 45
  • 67

1 Answers1

1

At time of writing this answer, the documentation also states that:

Note

Array.prototype.sort() doesn't support arguments.

So you are basically stuck with the default array sort, which sorts in place in ascending order :/

A bit disappointing isn't it?

I'm afraid your best guess would be to implement your own sorting function.

Raph
  • 326
  • 3
  • 15