js/ts 정렬 한글, 영문, 숫자 순

백경·2022년 6월 10일
0

문자열을 정렬해야할 경우 사용하는 함수를 만들어보자.

한글, 영문, 숫자의 순으로 정렬을 하고
그 안에서는 오름 차순으로 정렬이 된다.

const patternAlphabet = /[a-zA-Z]/
const isAlphaBet = (s: string) => patternAlphabet.test(s.charAt(0))

const list = ['ㄷ', 'ㄴ', 'ㅋ', 'z', 'a', 'b', '1', 'ㄱ', 'ㅎ', 'Z', 'z', 'ㅠ', 's']

const patternNumber = /[0-9]/
const patternAlphabet = /[a-zA-Z]/
const patternHangul = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/
const orderLevelDesc = [patternNumber, patternAlphabet, patternHangul]
// 배열의 역순으로 정렬이 된다.

const getLevel = (s: string) => {
  const index = orderLevelDesc.findIndex((pattern) => pattern.test(s))
  return index;
}

const sortGroupString = (source: string[]) => {
  // console.log('[removeDulicate] source', source)
  source.sort((a, b) => {
    const aLevel = getLevel(a.charAt(0))
    const bLevel = getLevel(b.charAt(0))
    if (aLevel === bLevel) {
      return a.charCodeAt(0) - b.charCodeAt(0)
    }
    return bLevel - aLevel; // 오름 차순 정렬 
  })
  // console.log('[sortGroupString] result', source)
}

// ['ㄱ', 'ㄴ', 'ㄷ', 'ㅋ', 'ㅎ', 'ㅠ', 'Z', 'a', 'b', 's', 'z', '1']
profile
Let me introduce myself as an FE developer.

0개의 댓글