我有一个JavaScript对象数组:

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

如何在JavaScript中按last_nom的值对它们进行排序?

我知道排序(a,b),但这似乎只适用于字符串和数字。是否需要向对象添加toString()方法?


当前回答

我知道已经有很多答案了,包括那些带有localeCompare的答案,但如果您出于某种原因不想/不能使用localeCompae,我建议您使用此解决方案,而不是三元运算符解决方案:

objects.sort((a, b) => (a.name > b.name) - (a.name < b.name));

有人可能会说,这段代码在做什么并不明显,但在我看来,三元运算符更糟糕。如果一个三元运算符足够可读,那么两个三元操作符一个嵌入另一个-真的很难读而且很难看。只有两个比较运算符和一个减号运算符的单行代码非常容易阅读,因此很容易推理。

其他回答

我遇到了排序对象数组的问题,改变了值的优先级。基本上,我想按年龄,然后按姓氏,或者仅仅按姓氏,名字来对一系列人进行排序。

我认为与其他答案相比,这是最简单的解决方案。

它用于调用sortPeoples(['array','of','properties'],reverse=false)。

///////////////////////人群示例阵列///////////////////////var人民=[{姓名:“Zach”,姓:“Emergency”,年龄:1},{姓名:“南希”,姓:“护士”,年龄:1岁},{姓名:“Ethel”,姓:“Emergency”,年龄:1},{姓名:“尼娜”,姓:“护士”,年龄:42岁},{姓名:“Anthony”,姓:“Emergency”,年龄:42岁},{姓名:“尼娜”,姓:“护士”,年龄:32岁},{姓名:“Ed”,姓:“Emergency”,年龄:28岁},{姓名:“彼得”,姓:“医生”,年龄:58岁},{姓名:“Al”,姓:“Emergency”,年龄:58岁},{姓名:“Ruth”,姓:“Registration”,年龄:62岁},{姓名:“Ed”,姓:“Emergency”,年龄:38岁},{姓名:“Tammy”,姓:“Triage”,年龄:29岁},{姓名:“Alan”,姓:“Emergency”,年龄:60岁},{姓名:“尼娜”,姓:“护士”,年龄:58岁}];////////////////////////排序功能/////////////////////函数sortPeoples(propertyArr,reverse){函数比较(a,b){变量i=0;while(propertyArr[i]){如果(a[propertyArr[i]]<b[propertyAr[i]])返回-1;如果(a[propertyArr[i]]>b[propertyAr[i]])返回1;i++;}返回0;}人民。排序(比较);if(反向){peoples.reverse();}};////////////////排序方法结束///////////////函数printPeoples(){$(“#输出”).html(“”);people.forEach(功能(人){$('#output').append(person.surname+“”+person.name+““”+person.age+“<br>”);})}<head><script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script></head><html><body><button onclick=“sortPeoples(['surname']);printPeoples()”>仅按姓氏ASC排序会导致同名案例的混乱</button><br><button onclick=“sortPeoples(['surname','name],true);printPeoples()”>按姓氏排序,然后按名称DESC</button><br><button onclick=“sortPeoples(['age']);printPeoples()”>按age ASC排序。与第一种情况相同的问题</button><br><button onclick=“sortPeoples(['age','姓']);printPeoples()”>按age和姓氏ASC排序。添加第二个字段修复了它。</button><br><div id=“output”></div></body></html>

您还可以创建一个动态排序函数,根据传递的值对对象进行排序:

function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        /* next line works with strings and numbers, 
         * and you may want to customize it to your needs
         */
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

所以你可以有一个这样的对象数组:

var People = [
    {Name: "Name", Surname: "Surname"},
    {Name:"AAA", Surname:"ZZZ"},
    {Name: "Name", Surname: "AAA"}
];

…当你这样做时,它会起作用:

People.sort(dynamicSort("Name"));
People.sort(dynamicSort("Surname"));
People.sort(dynamicSort("-Surname"));

事实上,这已经回答了问题。下面的部分是因为许多人联系我,抱怨它不适用于多个参数。

多个参数

您可以使用下面的函数生成具有多个排序参数的排序函数。

function dynamicSortMultiple() {
    /*
     * save the arguments object as it will be overwritten
     * note that arguments object is an array-like object
     * consisting of the names of the properties to sort by
     */
    var props = arguments;
    return function (obj1, obj2) {
        var i = 0, result = 0, numberOfProperties = props.length;
        /* try getting a different result from 0 (equal)
         * as long as we have extra properties to compare
         */
        while(result === 0 && i < numberOfProperties) {
            result = dynamicSort(props[i])(obj1, obj2);
            i++;
        }
        return result;
    }
}

这将使您能够执行以下操作:

People.sort(dynamicSortMultiple("Name", "-Surname"));

子类化数组

对于我们中能够使用ES6的幸运者,ES6允许扩展本机对象:

class MyArray extends Array {
    sortBy(...args) {
        return this.sort(dynamicSortMultiple(...args));
    }
}

这将实现:

MyArray.from(People).sortBy("Name", "-Surname");

这里有很多好的答案,但我想指出,它们可以非常简单地扩展,以实现更复杂的排序。您必须做的唯一一件事就是使用OR运算符来链接比较函数,如下所示:

objs.sort((a,b)=> fn1(a,b) || fn2(a,b) || fn3(a,b) )

其中fn1,fn2。。。是返回[-1,0,1]的排序函数。这导致“按fn1排序”和“按fn2排序”,这在SQL中相当于ORDERBY。

此解决方案基于||运算符的行为,该运算符的求值结果为第一个可转换为true的求值表达式。

最简单的表单只有一个这样的内联函数:

// ORDER BY last_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) )

使用last_nom和first_nom排序顺序有两个步骤,如下所示:

// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) ||
                  a.first_nom.localeCompare(b.first_nom)  )

通用比较函数可以是这样的:

// ORDER BY <n>
let cmp = (a,b,n)=>a[n].localeCompare(b[n])

此函数可以扩展为支持数字字段、区分大小写、任意数据类型等。

您可以通过按排序优先级链接它们来使用它们:

// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> cmp(a,b, "last_nom") || cmp(a,b, "first_nom") )
// ORDER_BY last_nom, first_nom DESC
objs.sort((a,b)=> cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )
// ORDER_BY last_nom DESC, first_nom DESC
objs.sort((a,b)=> -cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )

这里的重点是,采用函数方法的纯JavaScript可以在没有外部库或复杂代码的情况下走很长的路。它也非常有效,因为不需要进行字符串解析。

编写短代码:

objs.sort((a, b) => a.last_nom > b.last_nom ? 1 : -1)

EgeÖzcan代码的其他描述参数:

function dynamicSort(property, desc) {
    if (desc) {
        return function (a, b) {
            return (a[property] > b[property]) ? -1 : (a[property] < b[property]) ? 1 : 0;
        }
    }
    return function (a, b) {
        return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
    }
}