performance - How to sort typed arrays in javascript? - Stack Overflow

For example I have typed array like this:var a = new Int32Array([3,8,6,1,6,9]);When I try to call a.sor

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?

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?

Share Improve this question asked Feb 18, 2014 at 0:20 LukaLuka 3,0904 gold badges21 silver badges34 bronze badges 3
  • 2 Have you tried [].sort.call(a)? – Felix Kling Commented Feb 18, 2014 at 0:25
  • 2 @Felix Kling: ^ the answer (I'd rather use Array.prototype.call though) – zerkms Commented Feb 18, 2014 at 0:28
  • 1 ES6 introduced TypedArray.prototype.sort: stackoverflow./a/37684611/1647737 – le_m Commented Jun 7, 2016 at 16:31
Add a ment  | 

2 Answers 2

Reset to default 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.

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 pare function:

[TypedArray.prototype.sort] performs a numeric parison rather than the string parison 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]

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745383832a4625351.html

相关推荐

  • performance - How to sort typed arrays in javascript? - Stack Overflow

    For example I have typed array like this:var a = new Int32Array([3,8,6,1,6,9]);When I try to call a.sor

    5小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信