-
문자열.charCodeAt(index)JavaScript/입 속의 검은 잎 2022. 9. 28. 00:30
35번과 36번 문자열 비교의 경우.
function solution(strings, n) { return strings.sort().sort((a,b) => a.charCodeAt(n) - b.charCodeAt(n)) }
-charCodeAt( index) 안의 index가 문자열의 그 index인 것이 헷갈렸었다.
-제한조건, "n번째 문자열이 같을 때는 본래의 사전순서대로" 라는 조건을 구현하려 시도하다가... 대단히 헤맸다. 어디까지 갔다왔나 몰라.
let s = "Zbcdefg" function solution(s) { let n = [...s] // ['Z', 'b', 'c','d', 'e', 'f', 'g'] return n.sort((a,b) => b.charCodeAt(0)-a.charCodeAt(0)).join('') } // bcdefgZ
-내림차순 정렬.
charCodeAt() 은 지정된 인덱스 문자의 UTF-16 정수를 반환한다.
예컨대 A의 유니코드 값은 65이다.
var ch = 'A'; var index = 0; var i = ch.charCodeAt(index); console.log(i); // 65
반대방향의 메서드. fromCharCode()
유니코드 65, 66에 해당하는 문자는 AB이다.
console.log(String.fromCharCode(65, 66)); // returns 'AB
아예 내가 35번에서 하려던걸 대신 해주는 메서드 string.localeCompare
function solution(strings, n) { // strings 배열 // n 번째 문자열 비교 return strings.sort((s1, s2) => s1[n] === s2[n] ? s1.localeCompare(s2) : s1[n].localeCompare(s2[n])); }
// "a"는 "c"의 앞에 오기 때문에 음수 값을 리턴 'a'.localeCompare('c'); // -2 or -1 (or some other negative value) //알파벳 순으로 "check"는 "against"의 뒤에 오기 때문에 양수 값을 리턴 'check'.localeCompare('against'); // 2 or 1 (or some other positive value) // "a"는 "a"와 같기 때문에 0 'a'.localeCompare('a'); // 0
'JavaScript > 입 속의 검은 잎' 카테고리의 다른 글
json 객체 (0) 2022.10.05 set() (0) 2022.09.28 map(parseInt) 가 NaN 으로 응답했을 때, 이 문제는 모종의 유적(類的) 문제틀로 인한 파생이 아닐까 하는... (1) 2022.09.26 만날 찾아봤다 까먹는 것1 : 숫자 쪼개서 배열 만들기 (0) 2022.09.26 array.equals : 배열끼리의 비교 (0) 2022.09.25