How do you sort an array on multiple columns?

前端 未结 16 1327
面向向阳花
面向向阳花 2020-11-22 13:02

I have a multidimensional array. The primary array is an array of

[publicationID][publication_name][ownderID][owner_name] 

What I am tryin

16条回答
  •  孤独总比滥情好
    2020-11-22 13:53

    String Appending Method

    You can sort by multiple values simply by appending the values into a string and comparing the strings. It is helpful to add a split key character to prevent runoff from one key to the next.

    Example

    const arr = [ 
        { a: 1, b: 'a', c: 3 },
        { a: 2, b: 'a', c: 5 },
        { a: 1, b: 'b', c: 4 },
        { a: 2, b: 'a', c: 4 }
    ]
    
    
    function sortBy (arr, keys, splitKeyChar='~') {
        return arr.sort((i1,i2) => {
            const sortStr1 = keys.reduce((str, key) => str + splitKeyChar+i1[key], '')
            const sortStr2 = keys.reduce((str, key) => str + splitKeyChar+i2[key], '')
            return sortStr1.localeCompare(sortStr2)
        })
    }
    
    console.log(sortBy(arr, ['a', 'b', 'c']))

提交回复
热议问题