简体   繁体   中英

Sort an array by its values

I have the following array.

var arr = ["1-5", "3-6", "2-4"];

Is there a way where I can sort like this:

var arr = ["1-5", "2-4", "3-6"]

I've tried with jquery map but cant because the values of array are not Numbers.

You can use sort function

Sort by first number

arr.sort(function (a, b) {

  //  a.split('-') - split a string into an array  - ['1', '5']
  //  a.split('-')[0] - get first element          - '1' 
  // "+" converts string to number                 - 1
  // the same for "b"

  return +a.split('-')[0] - +b.split('-')[0]; 
});

Example

Sort by second number

arr.sort(function (a, b) {
  return +a.split('-')[1] - +b.split('-')[1];
});

Example

Use array sort. First the first num is compared. If they are equal, the second num is compared..

 var arr = ["1-5", "3-6", "2-4"]; var sorted = arr.sort(function(a,b){ var numsA = a.split('-'); var numsB = b.split('-'); if (numsA[0]-numsB[0] !== 0){ return numsA[0] - numsB[0]; } return numsA[1] - numsB[1]; }); document.write(sorted); 

You can try the built in sort functionality arr.sort()

http://jsfiddle.net/qctg9cfx/

If sorting by the first number in the string, and also if the first number could itself be negative then a more robust solution may be to use parseInt .

 var arr = ["1-5", "3-6", "-1-3", "2-4"]; arr.sort(function (a, b) { return parseInt(a, 10) - parseInt(b, 10); }); document.body.appendChild(document.createTextNode(JSON.stringify(arr))); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM