Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort function. Sort by First then by Second

I have an array of objects to sort. Each object has two parameters: Strength and Name

objects = [] object[0] = {strength: 3, name: "Leo"} object[1] = {strength: 3, name: "Mike"} 

I want to sort first by Strength and then by name alphabetically. I am using the following code to sort by the first parameter. How do I sort then by the second?

function sortF(ob1,ob2) {   if (ob1.strength > ob2.strength) {return 1}   else if (ob1.strength < ob2.strength){return -1}   return 0; }; 

Thanks for your help.

(I am using Array.sort() with the aforementioned sortF as the sort comparison function passed into it.)

like image 480
Leonardo Amigoni Avatar asked Feb 07 '12 11:02

Leonardo Amigoni


People also ask

What is JavaScript sort order?

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.


1 Answers

Expand your sort function to be like this;

function sortF(ob1,ob2) {     if (ob1.strength > ob2.strength) {         return 1;     } else if (ob1.strength < ob2.strength) {          return -1;     }      // Else go to the 2nd item     if (ob1.name < ob2.name) {          return -1;     } else if (ob1.name > ob2.name) {         return 1     } else { // nothing to split them         return 0;     } } 

A < and > comparison on strings is an alphabetic comparison.

like image 157
Matt Avatar answered Sep 28 '22 10:09

Matt