最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort array in ascending order based on ints and not strings - Stack Overflow

programmeradmin2浏览0评论

I have an array with this structure:

myArray = [ [<number>, [<string>] ], [<number>, [<string>] ], ... ];

I'd like to sort the array according to the ints. Unfortunately, when I call .sort() on myArray it returns me an array sorted according to the strings. How could I solve this?

I have an array with this structure:

myArray = [ [<number>, [<string>] ], [<number>, [<string>] ], ... ];

I'd like to sort the array according to the ints. Unfortunately, when I call .sort() on myArray it returns me an array sorted according to the strings. How could I solve this?

Share Improve this question asked Apr 29, 2013 at 13:33 Federico CapelloFederico Capello 1,1183 gold badges12 silver badges21 bronze badges 1
  • Mix Sorting objects in an array by a field value in JavaScript with sort a javascript array of numbers (didn't found the exact dupe of this) – Bergi Commented Apr 29, 2013 at 13:38
Add a ment  | 

2 Answers 2

Reset to default 6

Try this

myArray.sort(function(a,b) {return a[0]-b[0]})

To perform a numeric sort, you must pass a function as an argument when calling the sort method.

var myarray=[[21,"aadfa"], [24,"ca"],[52,"aa"], [15,"ba"]]
myarray.sort(function(a,b){return a[0] - b[0]})

you can find more information about it on http://www.javascriptkit./javatutors/arraysort.shtml

The function specifies whether the numbers should be sorted ascending or descending.

Here you have more examples http://www.w3schools./jsref/jsref_sort.asp

发布评论

评论列表(0)

  1. 暂无评论