According to an object in the array to the array or more attributes of the sort

This article describes how to sort by one or more properties to an array of objects.

demand

Background returned data to display a certain sequence, according to which one or more property attributes.

Solution

  • Sorting single property

    // 创建动态排序函数,根据传递的值对对象进行排序:
    function dynamicSort(property) {
        var sortOrder = 1;
        if(property[0] === "-") {
            sortOrder = -1;
            property = property.substr(1)
        }
        return function (a,b) {
            // 下面一行代码对字符串和数字均有效
            // 你可以根据自己的需求定制它
            var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0
            return result * sortOrder
        }
    }
    
    // 待处理数据
    var data = [
        {name: 'tom4', mdate: '202012'},
        {name:'tom2', mdate:'202001'},
        {name: 'tom1', mdate: '202008'},
        {name: 'tom3', mdate: '202005'}
    ]
    
    // 使用:按照属性 mdate 给data排序
    let sortedArr = data.sort(dynamicSort("mdate"))
    
    
  • Multi-attribute sorting

    function dynamicSortMultiple() {
        /*
         * 保存arguments对象,因为它将被覆盖
         * 注意arguments对象是一个类似数组的对象
         * 由要排序的属性的名称组成
         */
        var props = arguments
        return function (obj1, obj2) {
            var i = 0, result = 0, numberOfProperties = props.length
            // 从0开始获取不同的结果,因为有多个属性需要比较
            while(result === 0 && i < numberOfProperties) {
                result = dynamicSort(props[i])(obj1, obj2)
                i++
            }
            return result
        }
    }
    
    // 使用:按照属性 name 和 mdate 给data排序
    let sortedArr = People.sort(dynamicSortMultiple("name", "mdate"));
    
  • It may also be used ES6, which allows extended native objects

    class MyArray extends Array {
        sortBy(...args) {
            return this.sort(dynamicSortMultiple.apply(null, args))
        }
    }
    
    // 使用:按照属性 mdate 给data排序
    let sortedArr = MyArray.from(data).sortBy("mdate")
    

Remark

  • Note that there are multiple attribute sorting line of code dynamicSort(props[i])(obj1, obj2), because dynamicSortthe function returns a function to perform this function it uses two brackets.
  • f () performs the f function, subroutine returns.
  • F () () subroutine execution, the function returns sun.
  • The deeper the more brackets execution

Guess you like

Origin www.cnblogs.com/codebook/p/12630026.html