How to sort typed arrays in javascript?

javascript, performance, typed-arrays

Solution

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.

Problem

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?

Original source

Related problems