ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 문자열과 숫자에 접근하는 방법들 2 : sort()
    JavaScript 2022. 9. 28. 19:14

    sort( ) 는 만만해보이지만 정말이지 어려운 메서드이다. 

    let strings = 	["sun", "bed", "car"]
    let n = 1
    
    
    console.log( strings.sort().sort((a,b) => a.charCodeAt(n) - b.charCodeAt(n)) ) 
    
    // [ 'car', 'bed', 'sun' ]

    1번째 인덱스의 문자 기준으로 sort 오름차순 정렬. 

    문자를 빼기 위해 유니코드 변환을 했다.


    let s = "Zbcdefg"
    
    let n = [...s]
    console.log(n) / ['Z', 'b', 'c','d', 'e', 'f','g']
    
    console.log(
        n.sort((a,b) => b.charCodeAt(0)-a.charCodeAt(0)).join('') ) // gfedcbZ

    내림차순 정렬. 글자 하나씩 쪼개어, 인덱스0으로 놓고(자기자신) 유니코드 값을 빼는 방식으로 정렬했다.

     

    물론 이것은 뻘짓인지도 몰라.

     

    function solution(s) {
      return s
        .split("")
        .sort()
        .reverse()
        .join("");
    }

    기본만 해도 가능하기 때문이다.

     


    String.prototype.localeCompare()

    비교적 최신의 메서드인지, 용례를 쉽게 찾아볼 수 없다.

    그러나 문자열 정렬시 아주 좋은 대안이 될 수 있다.

     

    function solution(strings, n) {
        // strings 배열
        // n 번째 문자열 비교
        return strings.sort((s1, s2) => s1[n] === s2[n] ? s1.localeCompare(s2) : s1[n].localeCompare(s2[n]));
    }

     

    잘 정리되어 있다고 모두가 야부리를 치지만 항상 정보 차원에서 머물고 별다른 지식은 제공해주지 않는 우리 Mozilia 사의 MDN 문서를 살펴보자.

     

    // The letter "a" is before "c" yielding a negative value
    'a'.localeCompare('c'); // -2 or -1 (or some other negative value)
    
    // Alphabetically the word "check" comes after "against" yielding a positive value
    'check'.localeCompare('against'); // 2 or 1 (or some other positive value)
    
    // "a" and "a" are equivalent yielding a neutral value of zero
    'a'.localeCompare('a'); // 0

     

    대충 문자값 잘 빼줬다는 이야기.  그러나 이 메서드는 그 이름에서도 그렇듯, 지역의 언어를 비교하기 위해 만들어졌다.

     

    let items = ['réservé', 'Premier', 'Cliché', 'communiqué', 'café', 'Adieu'];
    items.sort( (a, b) => a.localeCompare(b, 'fr', {ignorePunctuation: true}));
    // ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']

    강세표시 무시 옵션을 걸고 수행한 프랑스어 정렬. 

    이후 다른 언어를 다룰 때 공부를 이어나가야할 함수이다.

Designed by Tistory.