How does one sort a multi dimensional array by multiple columns in JavaScript?

前端 未结 5 895
梦谈多话
梦谈多话 2020-12-09 19:38

I\'ve been working on this problem all day without a good solution. Google has been little help as well. I have a script that needs to accept a two dimensional array with

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 19:59

    There are already good answers to this question, would like to add a short functions to handle multiple key array sort inspired solution of https://stackoverflow.com/users/2279116/shinobi.

    // sort function handle for multiple keys
    const sortCols  = (a, b, attrs) => Object.keys(attrs)
        .reduce((diff, k) =>  diff == 0 ? attrs[k](a[k], b[k]) : diff, 0);
    

    Let's take an following example

    const array = [
        [1, 'hello', 4],
        [1, 'how', 3],
        [2, 'are', 3],
        [1, 'hello', 1],
        [1, 'hello', 3]
    ];
    
    array.sort((a, b) => sortCols(a, b, { 
       0: (a, b) => a - b, 
       1: (a, b) => a.localeCompare(b), 
       2: (a, b) => b - a
    }))
    

    The output would be following.

    [ 1, "hello", 4 ]​
    [ 1, "hello", 3 ]​
    [ 1, "hello", 1 ]​
    [ 1, "how", 3 ]
    ​[ 2, "are", 3 ]
    

提交回复
热议问题