Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort typed arrays in javascript?

For example I have typed array like this:

var a = new Int32Array([3,8,6,1,6,9]);

When I try to call a.sort(), it doesn't work.

What is the best way to sort typed arrays? What about performance, can we sort typed arrays faster than regular arrays?

like image 337
Luka Avatar asked Feb 18 '14 00:02

Luka


2 Answers

JavaScript array methods are defined in such a way that they are applicable to any array-like object, not only to actual instances of Array. So you can use:

Array.prototype.sort.call(a, function(a, b) { return a - b; });

The custom callback is necessary because JS sorts the values lexicographically by default. See also How to sort an array of integers correctly.

like image 181
Felix Kling Avatar answered Oct 19 '22 02:10

Felix Kling


The ECMAScript 2015 Language Specification introduced a .sort() method for typed arrays.

var a = new Int32Array([3, 8, 6, 1, 6, 9]);
console.log(a.sort()); // [1, 3, 6, 6, 8, 9]

There are some differences though, e. g. regarding the default compare function:

[TypedArray.prototype.sort] performs a numeric comparison rather than the string comparison used in [Array.prototype.sort].

console.log(new Array([1, 10, 2]).sort()); // [1, 10, 2]
console.log(new Int32Array([1, 10, 2]).sort()); // [1, 2, 10]
like image 3
le_m Avatar answered Oct 19 '22 04:10

le_m