Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 262
dmnkhhn Avatar asked Mar 25 '11 16:03

dmnkhhn


People also ask

How do you sort an array inside an array?

sort() , like so: var sortedArray = array. sort(function(a, b) { return a - b; }); This would sort an array of integers in ascending order.

Does arrays sort work with strings?

To sort an array of strings in Java, we can use Arrays. sort() function.

How do you sort an array of strings?

To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.

How do you sort an array of strings in ascending order?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


2 Answers

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);
like image 172
Martin Milan Avatar answered Sep 22 '22 23:09

Martin Milan


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; }); 
like image 38
vhallac Avatar answered Sep 21 '22 23:09

vhallac