javascript multi sorter 객체를 두개 이상의 key로 정렬

치즈말랑이·2022년 11월 3일
0

참고: https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields

a 배열과 같은 것을 앞 연도와 뒤 시즌으로 각각 정렬을 해야되서 검색을 해봤는데, 스택오버플로우에 fieldSorter 알고리즘이 있었다. 이 알고리즘은 객체만 적용이 되서 배열을 객체로 바꿔주었다.

let a = ["22FW", "22SS", "19SS", "19FW", "18FW", "18SS", "20SS", "20FW", "CARRYOVER", "CO", "21FW", "21SS"]
const year_regex = /[\d]+/i
const season_regex = /[\D]+/i
a = a.map(e => {
    const season = e.match(season_regex)?.[0]
    const year = e.match(year_regex)?.[0]

    return {full_season: e, year: year || '', season: season || ''}
})


const fieldSorter = (fields) => (a, b) => fields.map(o => {
    let dir = 1;
    if (o[0] === '-') { dir = -1; o=o.substring(1); }
    return a[o] > b[o] ? dir : a[o] < b[o] ? -(dir) : 0;
}).reduce((p, n) => p ? p : n, 0);

const c = a.sort(fieldSorter(['-year', 'season']))

console.log(c)

fieldSorter를 보면 처음 괄호 안의 파라미터는 fields로 받고, 두번째 괄호 안의 파라미터는 sort 내부에서 생성되는 (a, b)를 받는다.
const c = a.sort(fieldSorter(['-year', 'season'])) 이건
const c = a.sort((a, b) => fieldSorter(['-year', 'season'])(a,b) ) 이것과 같기때문이다.
map함수 안에서 return 하는 값을 봤는데, 규칙을 알 수 없게 나오긴한다.
알고리즘 표현 방식이 복잡하긴 하지만, 급하게 여러 값 정렬을 사용해야할때에는 유용해보인다.

profile
공부일기

0개의 댓글