Sort array by last character
Complete the function to sort a given array or list by last character of elements.
Element can be an integer or a string.
['acvd', 'bcc'] --> ['bcc', 'acvd']
The last characters of the strings are d and c. As c comes before d, sorting by last character will give ['bcc', 'acvd'].
If two elements don't differ in the last character, then they should be sorted by the order they come in the array.
배열의 요소의 마지막 글자를 기준으로 정렬을 해라
function sortMe(arr) {
return [...arr].sort((a, b) => {
const [x, y] = [a.toString().slice(-1), b.toString().slice(-1)];
if (x !== y) return x.localecompare(y);
else {
return arr.indexOf(a) - arr.indexOf(b)
}
})
}
스프레드 연산자를 이용해 얉은 복사를 이용했다.
slice(-1)
길이와 상관없이 가장 마지막 글자를 뽑아낸다.
그것을 구조분해 문법을 통해 각각의 변수에 할당했다.
function sortMe(arr) {
let a;
for (let i = 0; i < arr.length-1; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i].toString().slice(-1) > arr[j].toString().slice(-1)) {
[arr[i], arr[j]] = [arr[j], arr[i]]
}
}
return arr;
}
어떻게 보면 가장 7kyu다운 문제풀이
구조분해 문법을 여기서도 사용하고 있다.