[codewars] sort array by last character

호두파파·2021년 6월 3일
0

알고리즘 연습

목록 보기
14/60

Description:

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.

Example:

  • ['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.

문제풀이

  • 숫자와 문자열이 혼합되어 있기 때문에 toString()을 이용해 숫자를 문자열로 바꿔줘야 함수가 제대로 동작할 수 있다.
function sortMe(arr){
  for(let i = 0; i < arr.length - 1; i++) {
    for (let j = i + 1; 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;
}

만약 첫 배열의 마지막 요소가 두번째 배열의 요소보다 크다면,
구조 분해를 통해 배열의 앞뒤를 바꿔주었다.

다른 문제풀이

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);
    }
  })
}

indexOF
문자열 내에서 특정한 문자열의 index 값을 리턴한다.

stringVale에서 특정한 문자열의 위치(index)를 반환한다.
탐색하려는 문자열이 존재하지 않는다면 -1을 반환한다.

profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글