I have an array of objects to sort. Each object has two parameters: Strength and Name
JavaScript
x
4
1
objects = []
2
object[0] = {strength: 3, name: "Leo"}
3
object[1] = {strength: 3, name: "Mike"}
4
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?
JavaScript
1
6
1
function sortF(ob1,ob2) {
2
if (ob1.strength > ob2.strength) {return 1}
3
else if (ob1.strength < ob2.strength){return -1}
4
return 0;
5
};
6
Thanks for your help.
(I am using Array.sort() with the aforementioned sortF as the sort comparison function passed into it.)
Advertisement
Answer
Expand your sort function to be like this;
JavaScript
1
17
17
1
function sortF(ob1,ob2) {
2
if (ob1.strength > ob2.strength) {
3
return 1;
4
} else if (ob1.strength < ob2.strength) {
5
return -1;
6
}
7
8
// Else go to the 2nd item
9
if (ob1.name < ob2.name) {
10
return -1;
11
} else if (ob1.name > ob2.name) {
12
return 1
13
} else { // nothing to split them
14
return 0;
15
}
16
}
17
A <
and >
comparison on strings is an alphabetic comparison.