풀이

function solution(strings, n) {
    strings.sort((a,b) =>{
        if(a[n] > b[n]){
            return 1;
        } else if(a[n] < b[n]){
            return -1;
        }else{
            if(a > b){
                return 1;
            }else{
                return -1;
            }
        }
    });

    return strings;
}

풀이를 진행하기 위해서 처음으로 sort매소드를 사용하여 n번째의 문자열을 비교하고 만약 같다면 사전식으로 비교해 주었다.

더 나은 풀이

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

한 문 장으로 간결하게 정렬하여 가져왔다.
3항 연산자를 사용하여 같을 때를 비교하고 같다면
localeCompare라는 매소드를 사용하여 문자열을 비교한다.
다르면 n번째를 localeCompare를 사용하여 비교한다.

localeCompare

이 메소드는 인자로 string을 받는다

// 같을 때는 0을 반환
'a'.localeCompare('a') // 0

// 사전 순으로 앞에 있을 때 -1을 반환
'a'.localeCompare('b') // -1

// 사전 순으로 뒤에 있을 때 1을 반환
'b'.localeCompare('a') // 1

+ Recent posts