https://school.programmers.co.kr/learn/courses/30/lessons/12915
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
처음 내가 테스트한 답은
function solution(strings, n) {
strings.sort((a, b) => {
return a[n] - b[n];
});
return strings;
}
이거였다.
제일 간과한 문제가 C언어와 다르게 자바스크립트에서는 문자열끼리 뺄 경우 ASCII코드로 자동 변환해서 빼주지 않고, NaN을 반환한다는것.
그래서 문자열의 ASCII코드를 가져오려면, charCodeAt()이라는 매소드를 사용해야 한다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt
String.prototype.charCodeAt() - JavaScript | MDN
The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
developer.mozilla.org
그래서 요렇게 바꿨는데,
function solution(strings, n) {
strings.sort((a, b) => {
return a.charCodeAt(n) - b.charCodeAt(n)
});
return strings;
}
이번엔 해당 배열의 알파벳이 같을 경우 나머지 알파벳으로 사전순으로 배열해야 한다는 제한조건이 있다는걸 뒤늦게 봤다.
그래서 a[n]의 코드를 비교하는 조건문을 추가해야 했고,
String.prototype.localeCompare() - JavaScript | MDN
The localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with Intl.Collator API support, this method simply calls Intl.Collator.
developer.mozilla.org
요렇게 좋고 편리한 매소드가 있다는 것도 알았다.
a.localeCompare(b)를 하면 sort에서 a-b하는것과 비슷한 값을 반환해서, a-b자리에 그대로 사용이 가능하다.ㅈ
(음수, 양수, 0을 반환하는 조건을 같지만, 브라우저마다 그 값이 1(-1)일수도 있고 2(-2)일수도 있다고 함. 차이의 크기를 비교할때 사용하면 안됨.)
function solution(strings, n) {
strings.sort((a, b) => {
return a[n]==b[n] ? a.localeCompare(b) : a[n].localeCompare(b[n]);
});
return strings;
}
이쁘게 삼항연산자도 쓰고, return문 안에 다 넣어버릴까 했는데, 너무 한줄이 길어질것 같아서 위로 빼놓았다.
다른사람 풀이를 봐도 거의 비슷하다. 매소드가 어떤게 있는지 잘 알아둬야겠다.