JavaScript sorting object
I have a JavaScript object (name, noWords, score, group)
flower - 1 - 88 - 0
flower - 1 - 99 - 0
flower,spring - 2 - 39 - 1
flower,spring - 2 - 58 - 1
flower,time - 2 - 20 - 2
flower,time - 2 - 53 - 2
spring,time - 2 - 55 - 3
flower,spring,time - 3 - 79 - 4
flower,spring,time - 3 - 121 - 4
I want to sort this object like this: first matter the number of words - it's made, then if there are more groups with the same number of words to sort by greater value of each 开发者_StackOverflow社区group
Expected result
flower - 1 - 88 - 0
flower - 1 - 99 - 0
flower,time - 2 - 20 - 2
flower,time - 2 - 53 - 2
spring,time - 2 - 55 - 3
flower,spring - 2 - 39 - 1
flower,spring - 2 - 58 - 1
flower,spring,time - 3 - 79 - 4
flower,spring,time - 3 - 121 - 4
assuming your objects are in an array, you can use a custom sort method for comparing two entries.
var myObjects = [ /* assuming this is filled. */ ];
myObjects.sort(function (a, b) {
// a and b will be two instances of your object from your list
// possible return values
var a1st = -1; // negative value means left item should appear first
var b1st = 1; // positive value means right item should appear first
var equal = 0; // zero means objects are equal
// compare your object's property values and determine their order
if (b.noWords < a.noWords) {
return b1st;
}
else if (a.noWords < b.noWords) {
return a1st;
}
// noWords must be equal on each object
if (b.group < a.group) {
return b1st;
}
else if (a.group < b.group) {
return a1st;
}
// group must be equal
// TODO continue checking until you make a decision
// no difference between objects
return equal;
});
Your description of how you want things ordered is unclear so I'll leave that part up to you.
First of all you mean Array
. You can't sort an Object
.
What you need is to perform an user sort. To do this you use the Array.sort()
method along with a custom sorting function. In that function you put you comparison algorithm.
Simple example:
myArray = [5, 3, 7, 9];
myArray.sort(function(a, b){
if(a > b)
return -1; // negative means that the elements are not in the right order and should be switched
else
return 1; // positive means that the element are in the desired order
});
The sort method does all the sorting for you but you have to provide the means of comparing any two elements.
精彩评论