我有一个组对象(name、noWords、score、JavaScript )
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我想像这样对这个对象进行排序:首先考虑单词的数量-它是这样产生的,然后如果有更多的组具有相同的单词数,则按每个组的较大值进行排序
预期结果
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发布于 2010-10-25 21:52:46
假设您的对象在数组中,您可以使用自定义排序方法来比较两个条目。
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;
});你对你想要的东西如何订购的描述不清楚,所以我把这部分留给你。
发布于 2010-10-25 17:57:01
首先,你指的是Array。不能对Object进行排序。
您需要的是执行用户排序。为此,您可以使用Array.sort()方法和自定义排序函数。在该函数中,您放置了比较算法。
简单的例子:
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
});sort方法为您完成所有排序,但您必须提供比较任意两个元素的方法。
https://stackoverflow.com/questions/4013422
复制相似问题