Sort an array with arrays in it by string
This can be achieved by passing a supporting function as an argument to the Array.sort
method call.
Something like this:
function Comparator(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
var myArray = [
[1, 'alfred', '...'],
[23, 'berta', '...'],
[2, 'zimmermann', '...'],
[4, 'albert', '...'],
];
myArray = myArray.sort(Comparator);
console.log(myArray);
You can still use array.sort()
with a custom function. Inside the function, simply compare the element that you want to use as your key. For you example, you could use:
myArray.sort(function(a, b) {
return a[1] > b[1] ? 1 : -1;
});
There´s an easier way now:
myArray = myArray.sort(function(a, b) {
return a[1].localeCompare(b[1]);
})
It is case insensitive too.
Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare