DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

Standardized way to sort a JSON array?

I know it can be very simple in Python.

sorted(arr)
# or sorted(arr, key=key_getter_fn)
Enter fullscreen mode Exit fullscreen mode

But what about JavaScript where JSON originated, or other programming languages (especially static-typed ones)?

If you don't know yet, in JavaScript, Array.prototype.sort sorts lexicographically if compare function is not defined.

var array1 = [1, 30, 4, 21, 100000, '3', '5', undefined, null, undefined];
array1.sort();
console.log(array1);
// output:
[1, 100000, 21, '3', 30, 4, '5', null, undefined, undefined]
Enter fullscreen mode Exit fullscreen mode

Of course, I can write a few lines of code, or import a JavaScript file, but how standard is it?

The usage is as simple as

var array1 = [1, 30, 4, 21, 100000, '3', '5', undefined, null, undefined]
sorted(array1)
console.log(array1)
// output:
[null, 1, 4, 21, 30, 100000, '3', '5', undefined, undefined]
Enter fullscreen mode Exit fullscreen mode

Why isn't one in the standard library, really?

Top comments (0)