TypedArray Sort Compares Numbers Not Strings

TypedArray.sort compares elements numerically while Array.sort falls back to string comparison, so the same digits sort differently in each.

JavascriptData Integrity

Code

javascriptsnippet
13 lines
// Regular Array.sort compares as STRINGS by default; TypedArray.sort
// compares numerically, because every element is already a number
const plain = [9, 80, 700];
console.log('array sort :', plain.sort().join(','));

const typed = Float64Array.from(plain);
console.log('typed sort :', typed.sort().join(','));

// TypedArray.sort accepts a comparator too, e.g. descending
console.log('typed desc :', typed.sort((a, b) => b - a).join(','));

// It mutates in place and returns the same view, like Array.sort
console.log('same object:', typed.sort() === typed);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

array sort : 700,80,9
typed sort : 9,80,700
typed desc : 700,80,9
same object: true

What the code does

Top-level bindings plain, typed hold the demo state — nothing sits inside a function scope.

What to watch for

  • The package manager never enters the picture for this snippet.

Applying it

Each step the file takes is announced in the output: array sort :, typed sort :, typed desc :.

Statements that decide the outcome

const typed = Float64Array.from(plain);
const plain = [9, 80, 700];

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Its state lives in module-level bindings: `plain`, `typed`.