繁体   English   中英

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

[英]How to sort an array of objects with multiple field values in JavaScript

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

按 JavaScript 中的字符串属性值对对象数组进行排序

使用该 function 可以完美地用于单一排序(在所有浏览器上),甚至可以在另一个排序中使用 Google Chrome 除外! 这是 Ege Özcan 的 arrays 对象的出色排序例程

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

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

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

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

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

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

有没有人知道在 Chrome 中也可以使用的排序中进行排序的更好方法?

我创建了该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/

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

例如:

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/

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

它允许您使用标准的Array.sort,但使用firstBy()。thenBy()。thenBy()样式。

我现在这篇文章很老了,无论如何我今天发现并引用了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"));

这是我的解决方案。 它比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));
};

 let obj = [{ name: "Gaurav" }, { name: "nidhu" }, { name: "Abhishek" }, { name: "cat" }, { name: "here" }]; for (let i = 0; i < obj.length; i++) { for (let j = 1; j < obj.length; j++) { if (obj[j - 1].name[0].toLowerCase() > obj[j].name[0].toLowerCase()) { let temp = obj[j - 1]; obj[j - 1] = obj[j] obj[j] = temp } } } console.log(obj)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM