Let’s say I have the following inventory and want to sort it by the 2nd element of each sub array of inventory. I could do that with the following:
var inventory = [
[ 5, 'Microphone' ],
[ 3, 'Hair Pin' ],
[ 88, 'Bowling Ball' ],
[ 2, 'Dirty Sock' ],
[ 7, 'Toothpaste' ],
[ 3, 'Half-Eaten Apple' ]
];
inventory.sort(function (a, b) {
if (a[1] > b[1]) {
return 1;
}
if (a[1] < b[1]) {
return -1;
}
return 0;
});
console.log(inventory);
The above would display the following in the console, which is what I wanted.
[ [ 88, ‘Bowling Ball’ ],
[ 2, ‘Dirty Sock’ ],
[ 3, ‘Hair Pin’ ],
[ 3, ‘Half-Eaten Apple’ ],
[ 5, ‘Microphone’ ],
[ 7, ‘Toothpaste’ ] ]
What if I want to see what happening to the inventory array at each step of the sort function? I could rewrite the sort callback function with some console.log statements to see how inventory is rearranged during/after each iteration of the sort.
var inventory = [
[ 5, 'Microphone' ],
[ 3, 'Hair Pin' ],
[ 88, 'Bowling Ball' ],
[ 2, 'Dirty Sock' ],
[ 7, 'Toothpaste' ],
[ 3, 'Half-Eaten Apple' ]
];
var iterationNum = 1;
inventory.sort(function (a, b) {
console.log();
console.log('iteration #'+iterationNum++);
console.log('inventory before comparing a[1] ('+a[1]+ ') and b[1] ('+b[1] +')');
console.log(inventory);
if (a[1] > b[1]) {
console.log('return 1 so '+ JSON.stringify(a) +' is located after ' + JSON.stringify(b));
return 1;
}
if (a[1] < b[1]) {
console.log('return -1 so '+ JSON.stringify(b) +' is located after ' + JSON.stringify(a));
return -1;
}
console.log('return 0 so nothing gets changed');
return 0;
});
console.log();
console.log('final inventory')
console.log(inventory);
See the following repl.it to see above code in action.