programmers12915
4097 단어 programmersalgorismalgorism
문자열 내 마음대로 정렬하기
문제 설명
문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때,
각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다.
예를 들어 strings가 ["sun", "bed", "car"]이고 n이 1이면
각 단어의 인덱스 1의 문자 "u", "e", "a"로 strings를 정렬합니다.
제한사항
1.strings는 길이 1 이상, 50이하인 배열입니다.
2. strings의 원소는 소문자 알파벳으로 이루어져 있습니다.
3. strings의 원소는 길이 1 이상, 100이하인 문자열입니다.
4. 모든 strings의 원소의 길이는 n보다 큽니다.
5. 인덱스 1의 문자가 같은 문자열이 여럿 일 경우,
사전순으로 앞선 문자열이 앞쪽에 위치합니다.
입출력 예
strings | n | return |
---|---|---|
["sun", "bed", "car"] | 1 | ["car", "bed", "sun"] |
["abce", "abcd", "cdx"] | 2 | ["abcd", "abce", "cdx"] |
function solution(strings, n) {
var answer = [];
answer = strings.sort((a, b) => {
if (a[n] === b[n]) {//n번째 값이 같은 경우
return a.localeCompare(b);//a와 b를 localeCompare한다.
} else {
return a[n].localeCompare(b[n]);//a[n]과 b[n]을 localeCompare한다.
}
});
console.log(strings);
return answer;
}
/*
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
*/
Author And Source
이 문제에 관하여(programmers12915), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@unow30/programmers12915저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)