문자열 before
와 after
가 매개변수로 주어질 때, before
의 순서를 바꾸어 after
를 만들 수 있으면 1을, 만들 수 없으면 0을 return 하도록 solution 함수를 완성해보세요.
string으로 되어있는 before
와 after
를 array로 바꾼다.
const beforeSort = [...before]
const afterSort = [...after]
비교하기 편하도록 before
after
배열을 오름차순으로 정렬한다.
function solution(before, after) {
const beforeSort = [...before].sort();
const afterSort = [...after].sort();
console.log(beforeSort);
console.log(afterSort);
}
function solution(before, after) {
const beforeSort = [...before].sort();
const afterSort = [...after].sort();
if (beforeSort === afterSort) {
return 1;
} else {
return 0;
}
}
제출을 했는데 오답이 나왔다.
찾아보니 자바스크립트의 모든 것은 객체이고, 배열 또한 객체이기 때문에 두 배열을 비교할 때 서로 값을 비교하는 것이 아니라 해당 배열의 참조를 체크하기 때문이다.
따라서 두 배열의 값을 서로 비교하기 위해서는, 오름차순으로 정렬한 배열을 다시 문자열로 변환해주면 두 배열을 문자 그대로 비교할 수 있게 된다.
function solution(before, after) {
const beforeSort = [...before].sort().join('');
const afterSort = [...after].sort().join('');
console.log(beforeSort);
console.log(afterSort);
if (beforeSort === afterSort) {
return 1;
} else {
return 0;
}
}
다시 문자열로 변환했더니 두 배열의 값들을 그대로 비교해주는 것을 확인할 수가 있다.