Reputation: 1224
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);
}
Upvotes: 1
Views: 1859
Reputation: 700242
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.
Upvotes: 3
Reputation: 59232
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());
}
Upvotes: 2