Sort an array with arrays in it by string
JavascriptArraysSortingJavascript Problem Overview
I have an array that contains several arrays and I would like to order the arrays based on a certain string within those arrays.
var myArray = [ [1, 'alfred', '...'],
[23, 'berta', '...'],
[2, 'zimmermann', '...'],
[4, 'albert', '...'],
];
How can I sort it by the name so that albert comes first and zimmermann comes last?
I know how I would do it if I could use the integer for sorting but the string leaves me clueless.
Thank for your help! :)
Javascript Solutions
Solution 1 - Javascript
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);
Solution 2 - Javascript
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;
});
Solution 3 - Javascript
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
Solution 4 - Javascript
In ES6 one might do the relatively pithy:
myArray.sort(([a], [b]) => a.localeCompare(b))
or
myArray.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
The helpful/modern bits being the =>
lambda operator, and the [X]
argument destructuring.
Solution 5 - Javascript
Awesome! Compound sort on first element, second element and then third, all ascending in this example, would be
myArray=myArray.sort(function(a,b){
retVal=0;
if(a[0]!=b[0]) retVal=a[0]>b[0]?1:-1;
else if(a[1]!=b[1]) retVal=a[1]>b[1]?1:-1;
else if(a[2]!=b[2]) retVal=a[2]>b[2]?1:-1;
return retVal
});
(multiple sort on more than one column)
Solution 6 - Javascript
Kept getting issues with the solutions posted here. For a simple sorter of simple strings inside an array, I used this:
arr = ["aaa","abc","aba"]
arr.sort((a, b) => a.localeCompare(b));
console.log(arr);
//['aaa','aba','abc']