我有一个 JavaScript 对象(名称、noWords、分数、组)
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
最佳答案
假设您的对象位于数组中,您可以使用自定义排序方法来比较两个条目。
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;
});
您对如何订购商品的描述不清楚,因此我将把这部分留给您。
关于JavaScript 排序对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4013422/