Sort List Numerically [JS1]

A JavaScript one-liner to sort a list of numbers


Description

A single line of JavaScript that takes a list of numbers and sorts them numerically. The list can come from a “Create list” action, or from text (one list item per line). List operations are surprisingly limited in Shortcuts. This snippet and others like it [1][2][3] try to fill this gap.

Your own sort method

The numerical sort is achieved by using a custom sort function:

(a,b)=>a-b

Other sortings can be used, but a clear criteria is needed. For example, to sort resolutions like 1280×720 and 1200×800, which of them goes first? If the criteria is "first width, then height" 1200×800 would go before 1280×720. But if the criteria is "amount of pixels", 1280×720 (922K pixels) would go before 1200×800 (960K pixels).

Don't download the shortcut

If you just want the code, there's no need to download the shortcut. Copy this and paste it in a "URL" action:

data:text/html,<script>let list=`REPLACETHISWITHLISTVARIABLE`;document.write(list.split("\n").sort((a,b)=>a-b).join('<br>'))</script>

Replace the REPLACETHISWITHLISTVARIABLE fragment with the variable contaning the list, add a "Get File of Type" with type com.apple.webarchive below, and split its output with new lines to get the sorted list.

I use "Get File of Type" instead of "Get Contents of Webpage" to avoid that the user is misleading told that the shortcut uses Safari.


Latest Release Notes

1.0.0 - Oct. 3, 2020, 8:40 a.m.

First public version