6

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?

3
  • 2
    Have you tried [].sort.call(a)? Commented Feb 18, 2014 at 0:25
  • 2
    @Felix Kling: ^ the answer (I'd rather use Array.prototype.call though) Commented Feb 18, 2014 at 0:28
  • 1
    ES6 introduced TypedArray.prototype.sort: stackoverflow.com/a/37684611/1647737 Commented Jun 7, 2016 at 16:31

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have compared sorting typed array this way, and regular array. It doesn't seem to have any significant difference in speed. Why is that? Shouldn't it be sorting typed array faster than regular array?
@dartfish Array.prototype.sort itself is extremely slow due to the obnoxious semantics it needs to implement. You are better off implementing a specialized sort yourself if you have even a little concern about performance.
3

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]

2 Comments

Where is that quote from? MDN page has no mention of that, aside from a comment in example code (which is hardly a part of spec).
@riv It's from the linked spec, under section 22.2.3.25 - ecma-international.org/ecma-262/6.0/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.