dmnkhhn dmnkhhn - 5 months ago 9
Javascript Question

Sort an array with arrays in it by string

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! :)

Answer

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);

I am not a Javascript wiz btw - use caution ...

Comments