4

I have an array of values like:

item1, item3, item2, item4, item5, item8, item6, item9, item10, item7, item11

When i sort them in javascript using .sort() i get the below result:

item1, item10, item11, item2, item3, item4, item5, item6, item7, item8, item9

I know this is because the items are strings and this what sort() is designed to do, but how can i sort them into the following?

item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11

thanks,

Sam Jones
  • 4,443
  • 2
  • 40
  • 45

4 Answers4

6

You can define your own .sort callback. In fact you need to do so to sort numbers. Your case is a bit different, though.

.sort(function (a, b) {
    return (+a.replace("item", "")) - (+b.replace("item", ""));
});

Demo: http://jsfiddle.net/Hbs8g/

In case item is not consistent, you can get the number part via .split(/(\d+)/)[1] assuming that the word part does not contain any numbers: http://jsfiddle.net/Hbs8g/1/

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

Sort takes a comparison function and will sort the list with it. After sort is called, the list is sorted.

z = ["item1", "item3", "item2", "item4", "item5", "item8", "item6", "item9", "item10", "item7", "item11"];    
z.sort(function(a, b) { return parseInt(a.substring(4)) - parseInt(b.substring(4)); });
anthonybell
  • 5,790
  • 7
  • 42
  • 60
0

Use Following:

var a = new Array();
a = ['item1', 'item3', 'item2', 'item4', 'item5', 'item8', 'item6', 'item9', 'item10', 'item7', 'item11'];
var temparray = new Array();
for (var i = 0; i < a.length; i++) {
    var substr = (a[i]).substring(4);
    temparray.push(parseInt(substr));
}
temparray.sort(function(a,b){return a-b});
 a=temparray;
console.log(a)
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
0

try this, if it is helpful to you

arr.sort(function(a, b) {
a = a.replace("item", "");
b = b.replace("item", "");
if (a > b)
   return 1;
else if (a < b)
   return -1;
else
   return 0;
});
Nitu Bansal
  • 3,826
  • 3
  • 18
  • 24