And it is trivial enough to swap the sort order by switching the returns or the if statements above.
But what if you need to sort an array of objects in a specific, non-alphabetical order?
An example I came across was to transfer some SQL data for importing to a database and the transfer needed to occur in a table-dependent way, so as to not break the table constraints of importing foreign keys that didn't exist yet.
So what's going on here?
The key is the importOrder.reduce() function. This is transforming the importOrder array into an object that creates a numerical order for each item in the original import array:
This then makes sorting the array much simpler by being able to directly look up an integer value for the sort position, which is what we are passing into the sort function of the tables array:
If you liked this post, please share it!