How do you sort an array on multiple columns?

前端 未结 16 1350
面向向阳花
面向向阳花 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:36

    I had a similar problem while displaying memory pool blocks from the output of some virtual DOM h-functions composition. Basically I faced to the same problem as sorting multi-criteria data like scoring results from players around the world.

    I have noticed that multi-criteria sorting is:

    - sort by the first column
    - if equal, sort by the second
    - if equal, sort by the third
    -  etc... nesting and nesting if-else
    

    And if you don't care, you could fail quickly in a if-else nesting hell... like callback hell of promises...

    What about if we write a "predicate" function to decide if which part of alternative using ? The predicate is simply :

    // useful for chaining test
    const decide = (test, other) => test === 0 ? other : test
    

    Now after having written your classifying tests (byCountrySize, byAge, byGameType, byScore, byLevel...) whatever who need, you can weight your tests (1 = asc, -1 = desc, 0 = disable), put them in an array, and apply a reducing 'decide' function like this:

    const multisort = (s1, s2) => {
      const bcs = -1 * byCountrySize(s1, s2) // -1 = desc 
      const ba =  1 *byAge(s1, s2)
      const bgt = 0 * byGameType(s1, s2) // 0 = doesn't matter
      const bs = 1 * byScore(s1, s2)
      const bl = -1 * byLevel(s1, s2) // -1 = desc
    
      // ... other weights and criterias
    
      // array order matters !
      return [bcs, ba, bgt, bs, bl].reduce((acc, val) => decide(val, acc), 0)
    }
    
    // invoke [].sort with custom sort...
    scores.sort(multisort)
    

    And voila ! It's up to you to define your own criterias / weights / orders... but you get the idea. Hope this helps !

    EDIT: * ensure that there is a total sorting order on each column * be aware of not having dependencies between columns orders, and no circular dependencies

    if, not, sorting can be unstable !

提交回复
热议问题