如何在JavaScript中对具有多个字段值的对象数组进行排序

时间:2012-07-07 23:08:20

标签: javascript sorting

我发现了一种很好的方法,可以根据以下定义的属性对对象数组进行排序:

Sort array of objects by string property value in JavaScript

使用该功能可以完美地用于单一排序(在所有浏览器上),甚至可以在另一种排序中使用Google Chrome进行排序!这是EgeÖzcan对物体阵列的伟大排序程序

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

使用名为“Data”的数组(当然,我的数组有更多对象)...

var Data = [{Category: "Business", Value: "ABC"},{Category:"Personal", Value:"XYZ"}];

通过这样做,我可以得到一个合适的排序,其中订单被列为每个类别中的所有值...

Data.sort(dynamicSort("Value"));
Data.sort(dynamicSort("Category"));

首先按Value排序,然后按Category排序,我的数组按排序顺序排列所有值,首先列出所有业务基础值,然后列出所有基于个人的值。完善!除了在Chrome中,数据按类别正确排序,但每个类别中的值的顺序似乎相当随机。

是否有人知道在Chrome中运行排序的更好方法?

5 个答案:

答案 0 :(得分:38)

我创建了该dynamicSort函数的多参数版本:

function dynamicSort(property) { 
    return function (obj1,obj2) {
        return obj1[property] > obj2[property] ? 1
            : obj1[property] < obj2[property] ? -1 : 0;
    }
}

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;
    }
}

我按如下方式创建了一个数组:

var arr = [
    {a:"a",b:"a",c:"a"},
    {a:"b",b:"a",c:"b"},
    {a:"b",b:"a",c:"a"},
    {a:"b",b:"a",c:"b"},
    {a:"b",b:"b",c:"a"},
    {a:"b",b:"b",c:"b"},
    {a:"b",b:"b",c:"a"},
    {a:"b",b:"b",c:"b"},
    {a:"b",b:"b",c:"a"},
    {a:"b",b:"b",c:"b"},
    {a:"b",b:"b",c:"a"},
    {a:"c",b:"b",c:"b"},
    {a:"c",b:"c",c:"a"}
];

当我这样做时它起作用了,

arr.sort(dynamicSortMultiple("c","b","a"));

这是一个有效的例子:http://jsfiddle.net/ZXedp/

答案 1 :(得分:6)

执行Javascript多标准排序(或多参数排序)的最简单方法是使用.sort,将多个参数连接在一起,并比较两个标记。

例如:

data.sort(function (a, b) {

  var aConcat = a["property1"] + a["property2"];
  var bConcat = b["property1"] + b["property2"];

  if (aConcat > bConcat) {
    return 1;
  } else if (aConcat < bConcat) {
    return -1;
  } else {
    return 0;
  }

});

我在这里添加了一个JsFiddle脚本:http://jsfiddle.net/oahxg4u3/6/

答案 2 :(得分:1)

您可能还想查看thenBy.js:https://github.com/Teun/thenBy.js

它允许你使用标准的Array.sort,但是使用firstBy()。thenBy()。thenBy()style。

答案 3 :(得分:1)

我现在这篇文章已经很老了,无论如何我今天发现并引用了EgeÖzcan,我改进了他的优秀解决方案,为感兴趣的人实现了DESC-ASC SQL-Like功能(http://jsfiddle.net/ZXedp/65/ ):

function dynamicSortMultiple() {
    var props=[];
    /*Let's separate property name from ascendant or descendant keyword*/
    for(var i=0; i < arguments.length; i++){
        var splittedArg=arguments[i].split(/ +/);
        props[props.length]=[splittedArg[0], (splittedArg[1] ? splittedArg[1].toUpperCase() : "ASC")];
    }
    return function (obj1, obj2) {
        var i = 0, result = 0, numberOfProperties = props.length ;
        /*Cycle on values until find a difference!*/
        while(result === 0 && i < numberOfProperties) {
            result = dynamicSort(props[i][0], props[i][1])(obj1, obj2);
            i++;
        }
        return result;
    }
}

/*Base function returning -1,1,0 for custom sorting*/
function dynamicSort(property, isAscDesc) { 
    return function (obj1,obj2) {
        if(isAscDesc==="DESC"){
            return ((obj1[property] > obj2[property]) ? (-1) : ((obj1[property] < obj2[property]) ? (1) : (0)));
        }
        /*else, if isAscDesc==="ASC"*/
        return ((obj1[property] > obj2[property]) ? (1) : ((obj1[property] < obj2[property]) ? (-1) : (0)));
    }
}

通过以下方式调用函数:

arr.sort(dynamicSortMultiple("c DESC","b Asc","a"));

答案 4 :(得分:0)

这是我的解决方案。它比lodash的 _。sortBy()多列排序函数快两倍(参见 http://jsperf.com/multi-column-sort。 我生成排序函数文本,然后在标准 .sort()中使用它。它也适用于Chrome和Firefox。

function multiColumnSort(arr,sf) {
    var s = '';
    sf.forEach(function(f,idx) {
        s += 'if(arguments[0].'+f+'>arguments[1].'+f+')return 1;';
        s += 'else if(arguments[0].'+f+'==arguments[1].'+f+')';
        s += (idx < sf.length-1)? '{' : 'return 0';
    });
    s += Array(sf.length).join('}')+';return -1';
    return arr.sort(new Function(s));
};