首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript排序对象

JavaScript排序对象
EN

Stack Overflow用户
提问于 2010-10-25 17:49:12
回答 2查看 118关注 0票数 0

我有一个组对象(name、noWords、score、JavaScript )

代码语言: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

我想像这样对这个对象进行排序:首先考虑单词的数量-它是这样产生的,然后如果有更多的组具有相同的单词数,则按每个组的较大值进行排序

预期结果

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-10-25 21:52:46

假设您的对象在数组中,您可以使用自定义排序方法来比较两个条目。

代码语言:javascript
复制
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;
});

你对你想要的东西如何订购的描述不清楚,所以我把这部分留给你。

票数 2
EN

Stack Overflow用户

发布于 2010-10-25 17:57:01

首先,你指的是Array。不能对Object进行排序。

您需要的是执行用户排序。为此,您可以使用Array.sort()方法和自定义排序函数。在该函数中,您放置了比较算法。

简单的例子:

代码语言:javascript
复制
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方法为您完成所有排序,但您必须提供比较任意两个元素的方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4013422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档