1

I have an array that contains numbers and strings:

disorderedArray = ["74783 Banana", "38903 Orange", "94859 Apple"];

I needed to put them in ascending order by number. I found an example that worked well for descending Sort Alphanumeric String Descending However, I can't seem to change the return line to make the array ascending. I tried to put arr.reverse(); after the return line, but that seemed kind of hackish and it didn't work anyways. I also changed the > and < symbols in the return line, but I started to get crazy results.

function sort() {
  var arr=disorderedArray;
  arr.sort(function(a,b){
    a=a.split(" ");
    b=b.split(" ");
    var an=parseInt(a[0],10);
    var bn=parseInt(b[0],10);
    return an<bn?1:(an>bn?-1:(a[1]<b[1]?-1:(a[1]>b[1]?1:0)));

    arr.reverse(); 

  });
  console.log(arr);
}   
Community
  • 1
  • 1
user3080392
  • 1,194
  • 5
  • 18
  • 35

2 Answers2

3

The callback function returns positive or negative values depending on the comparison of the values. Just change the sign of the -1 and 1 values that are returned:

return an<bn?-1:(an>bn?1:(a[1]<b[1]?1:(a[1]>b[1]?-1:0)));

Here is a more readable way to write the same:

return (
  an < bn ? -1 :
  an > bn ? 1 :
  a[1] < b[1] ? 1 :
  a[1] > b[1] ? -1 :
  0
);

Note that the original code sorts the numeric part descending and the rest of the string ascending, so this does the opposite. The value from the first two comparisons determine how the numeric part is sorted, and the last two determine how the rest of the strings are sorted, so you can adjust them to get the desired combination.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • This worked great. Thanks. I knew it had to do with reversing one of the symbols in the return line, but I highly doubt I would have figured that out through trial and error. – user3080392 Dec 19 '14 at 10:57
  • How would I change the order of the words from a to z instead of z to a. For example, with the code you gave it puts the alphanumeric array like: ["111 zucchini", "111 orange", "111 apple"]. How would I do: ["111 apple", "111 orange", "111 zucchini"] – user3080392 Dec 21 '14 at 15:10
  • @user3080392: You would swap the `1` and `-1` in the last comarisons; where `a[1]` and `b[1]` are compared. – Guffa Dec 21 '14 at 16:10
2

sort's function is just to sort. You need to call reverse on the sorted array.

function sort() {
    var arr = disorderedArray;
    arr.sort(function(a, b) {
        a = a.split(" ");
        b = b.split(" ");
        var an = parseInt(a[0], 10);
        var bn = parseInt(b[0], 10);
        return an < bn ? 1 : (an > bn ? -1 : (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0)));
    });
    console.log(arr.reverse());
}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95