jsrosetta

Collections

Sorting arrays

Node.js's Array.prototype.toSorted compared to in-place sorting in Go, Rust, and Java, and Swift's sort()/sorted().

Minimum versions
Node.js ≥ 20Go ≥ 1.21Rust ≥ 1.58Swift ≥ 3.0Java ≥ 25
Verified on
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Node.js code is an ES module: save it as .mjs or set "type": "module" in package.json.

Sorting numbers and strings in Node.js uses the same toSorted function with a comparator; Go splits this into two cases: slices.Sort for types with a natural order (cmp.Ordered), and slices.SortFunc for custom comparisons, such as sorting by a struct field. Rust and Java only sort in place (sort/sort_by_key, Collections.sort) — to keep the original untouched, copy it first, just like Go. Swift has both: sort()/sort(by:) sorts in place, and sorted()/sorted(by:) returns a new array without touching the original — a direct equivalent of JavaScript's toSorted().

Sorting numbers and strings

const stringArray = ['a', 'd', 'z', 'b', 'c', 'y']
const stringSortedAsc = stringArray.toSorted((a, b) => (a > b ? 1 : -1))
console.log(stringSortedAsc) // ['a', 'b', 'c', 'd', 'y', 'z']
 
const numberArray = [1, 3, 5, 9, 4, 2, 0]
const numberSortedAsc = numberArray.toSorted((a, b) => a - b)
console.log(numberSortedAsc) // [0, 1, 2, 3, 4, 5, 9]
 
const numberSortedDesc = numberArray.toSorted((a, b) => b - a)
console.log(numberSortedDesc) // [9, 5, 4, 3, 2, 1, 0]

Sorting by an object/struct field

const collection = [
  { name: 'Li L', age: 8 },
  { name: 'Json C', age: 3 },
  { name: 'Zack W', age: 15 },
  { name: 'Yi M', age: 2 }
]
 
const sortedByAge = collection.toSorted((a, b) => a.age - b.age)
console.log(sortedByAge)
// [{ name: 'Yi M', age: 2 }, { name: 'Json C', age: 3 }, { name: 'Li L', age: 8 }, { name: 'Zack W', age: 15 }]

Key differences

Node.js Go Rust Swift Java
Leaves the original untouched toSorted() slices.Clone before slices.Sort .clone() before .sort() .sorted()/.sorted(by:) copy constructor before Collections.sort, or .stream().sorted().toList()
Default comparison (no function) coerces to string compile error if the type isn't cmp.Ordered compile error if the type doesn't impl Ord compile error if the type isn't Comparable compile error if the type doesn't implement Comparable
Sorting by a field comparator function slices.SortFunc + cmp.Compare .sort_by_key / .sort_by .sort(by:) with a closure Comparator.comparingInt/.comparing
Reversing order comparator with flipped sign slices.Reverse .reverse() .reverse() Collections.reverse

Reference: github.com/miguelmota/golang-for-nodejs-developers#array-sorting