Sorting 2d Arrays Containing Numbers And Strings
I have an Inventory as shown below. var arr1 = [ [21, 'Bowling Ball'], [2, 'Dirty Sock'], [1, 'Hair Pin'], [5, 'Microphone'] ]; I want to sort the inventory alphab
Solution 1:
You may use the build in method Array#sort
with a custom callback.
The
sort()
method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
var arr1 = [[1, "Hair Pin"], [21, "Bowling Ball"], [2, "Dirty Sock"], [5, "Microphone"]];
arr1.sort(function (a, b) {
return a[1].localeCompare(b[1]);
});
document.write('<pre>' + JSON.stringify(arr1, 0, 4) + '</pre>');
Post a Comment for "Sorting 2d Arrays Containing Numbers And Strings"