My first question on this topic was answered and it helped me move forward so I apologize if this seems like it’s duplicate. I’ve moved forward from the 1st example and am now trying to Rank elements in a nested array based on values at postion (1) in each element of the nested array. The following works great with a number array.
function mySorting(a, b) {
return a == b ? 0 : (b < a ? -1 : 1)
}
var myArray = [28, 92, 12, 12, 2];
myArray.sort(mySorting);
var ranks = $.grep(myArray, function(item, idx) {
return item != myArray[idx - 1];
}).reverse();
$.each(myArray, function(idx, item) {
var rank= $.inArray( item, ranks)+1;
$('body').append('Rank of '+item+ ' is '+ rank+'<br>')
})
My problem is when I change the array to:
var myArray = [["textA",28], ["textB",92], ["textC",12], ["textD",12], ["textE",2]];
my sorting function no longer works. Can anyone help me out or point me in the right direction? I would like to sort “myArray” based of the number value in each nested element.
Thanks much once again in advance.
The arguments passed to the sorting function are whatever is contained in the array to be sorted. Your new array contains two-element arrays, so that’s what the sorting function will receive when you sort the array.
You say you want to sort the two-element arrays according to their second element. To do that, you should change your sorting function to look like this:
Edit: If you want to assign the same rank to all arrays with the same second element, you’ll also need to modify the rest of your code to only consider the second element when comparing arrays. Actually, it would probably be easiest to keep the sorting as it was, but just throw away everything but the second element before ranking the arrays: