0

I need to sort a list that's alphanumeric, but it's botching the multi-digit integers since it's character-by-character and 1 is less than 8.

Any it's particularly tricky because there can be alphabetic characters before and after the numbers. So if it can somehow understand the full integer instead of just the single digit then that would do it.

Normal Sort

  1. Grade 10 Academic
  2. Grade 10 Applied
  3. Grade 11
  4. Grade 8
  5. Grade 9

Desired Sort:

  1. Grade 8
  2. Grade 9
  3. Grade 10 Academic
  4. Grade 10 Applied
  5. Grade 11

Anyone know how to make a Javascript script to sort this way? Or even better if you have an AngularJS solution since I'm using that.

Thanks in advance for any help you can offer.

think.arthur
  • 695
  • 1
  • 7
  • 14

1 Answers1

0
var arr = [
  "Grade 10 Applied",
  "Grade 10 Academic",
  "Grade 11",
  "Grade 11 Testy",
  "Grade 9",
  "Grade 8"
];

alert(arr.sort(function(a, b) {
  // split the strings into arrays of words
  var aParts = a.split(' ');
  var bParts = b.split(' ');
  // compare the corresponding words, if they are integers parseInt first
  for(var i=0; i < Math.min(aParts.length, bParts.length); i++) {
    var aPart = /\d+/.test(aParts[i]) ? parseInt(aParts[i]) : aParts[i];
    var bPart = /\d+/.test(bParts[i]) ? parseInt(bParts[i]) : bParts[i];
    if(aPart === bPart) { continue; }
    return aPart < bPart ? -1 : 1;
  }
  // fall back to using the array's length
  // ["dog", "cat"] < ["dog", "cat", "frog"]
  return aParts.length - bParts.length
}).join('\n'));
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62