[Javascript] 프로그래머스 : 문자열 내 마음대로 정렬하기
[Javascript] 프로그래머스 Level 1 _ 문자열 내 마음대로 정렬하기
👇🏻
👇🏻
시행착오
( + 코드를 작성하면서든 생각들.)
1.
문자열 배열의 문자열과 n번째에 해당하는 문자
두가지를 저장하는 객체들로 이루어진 배열을 생성한 뒤
문자 기준으로 정렬한 후 문자열만 다시 배열에 저장해서 리턴했다!
function solution(strings, n) {
function Extract(string, n) {
this.string = string;
this.word = string[n];
}
let arr = [];
for(let i in strings) {
arr.push(new Extract(strings[i], n));
}
arr.sort(function(a, b) {
if(a.word > b.word){
return 1;
}
else if(b.word > a.word){
return -1;
}
else if(a.word == b.word){
return (a.string > b.string)? 1 : -1;
}
});
for(let i in strings){
strings[i] = arr[i].string;
}
return strings;
}
2.
다시 배열로 저장해서 리턴하는 과정에서 불필요한 과정을 거치는 것 같아서
map을 이용해서 문자열에 해당하는 것들을 배열으로 리턴하도록 수정했다!
function solution(strings, n) {
function resort(a,b){
if(a.word > b.word){
return 1;
}
else if(a.word < b.word){
return -1;
}
else if(a.word == b.word){
return (a.string > b.string)? 1 : -1;
}
}
function Extract(string, n) {
this.string = string;
this.word = string[n];
}
let arr = [];
for(let i in strings) {
arr.push(new Extract(strings[i], n));
}
return arr.sort((a,b) => resort(a,b)).map(a => a.string);
}
3.
객체 배열을 생성하고 정렬을 한 뒤 다시 리턴하는 과정이 불필요한 것 같아서
그냥 제시 기준에 맞는 배열 정렬을 위한 compareFunction만 정의했다!
function solution(strings, n) {
function resort(a,b){
if(a[n] > b[n]){
return 1;
}
else if(b[n] > a[n]){
return -1;
}
else if(a[n] == b[n]){
return (a > b)? 1 : -1;
}
}
return strings.sort((a,b) => resort(a, b));
}
1번 방법을 사용했을 때는 0.11ms ~ 0.16ms 가 나왔는데
2번 map을 사용했을 때 오히려 코드는 짧아졌지만 0.12ms ~ 0.37ms가 나왔다 신기하당.
마지막으로 3번째는 역시 0.07ms ~ 0.17ms로 가장 빨랐다...!
다른 분들은 localeCompare()를 사용하셨던데,,,,,ㅎ
오늘 처음 본 함수라 ㅎㅎㅎㅎㅎㅎㅎㅎㅎ 생각치도 못했다
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.
developer.mozilla.org
⚠️ 아래 내용은 모두 개인적인 참고 / 기록을 위한 용도입니다. 참고해주시고 편안하게 봐주세요 :) ⚠️
*** 혹시라도 잘못된 정보가 있다면 언제든지 알려주시면 감사하겠습니다 ! ***