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

前端 未结 5 1839
迷失自我
迷失自我 2020-12-10 13:56

I found a great method to sort an array of objects based on one of the properties as defined at:

Sort array of objects by string property value in JavaScript

5条回答
  •  無奈伤痛
    2020-12-10 14:21

    I created a multi-parameter version of that dynamicSort function:

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

    I created an array as follows:

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

    and it worked when I did,

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

    And here is a working example: http://jsfiddle.net/ZXedp/

提交回复
热议问题