How do you sort an array on multiple columns?

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

    I have just published to npm a micro-library called sort-helper (source on github). The idea is to import the helper by to create the comparison function for sort array method through the syntax items.sort(by(column, ...otherColumns)), with several way to express the columns to sort by:

    • By key: persons.sort(by('lastName', 'firstName')),
    • By selector: dates.sort(by(x => x.toISOString())),
    • In descending order: [3, 2, 4, 1].sort(by(desc(n => n)))[3, 2, 1, 0],
    • Ignoring case: ['B', 'D', 'c', 'a'].sort(by(ignoreCase(x => x))).join('')'aBcD'.

    It's similar to the nice thenBy mentioned in this answer but with the following differences that may be more to the taste of some:

    • An approach more functional than object-oriented (see thenBy fluent API),
    • A syntax a bit terser and still as much readable, natural almost like SQL.
    • Fully implemented in TypeScript, to benefit from type safety and type expressivity.

提交回复
热议问题