[JS] 자바스크립트의 sort()

EJ__OH·2022년 3월 18일
0

코테를 준비하면서, 알고리즘 공부해보면서, 혹은 실제로 개발하면서 sort() 요 함수 친구 많이 사용하게 됨.
특히 이 글을 쓰게 된건 코테 준비하면서 정렬할 일이 많았기에 쓰게됨.
문자열 정렬은 당연하고 숫자로 된 배열을 정렬할 일이 많은데 내 생각대로 되지 않아 당황함...

sort()는 문자 정렬!

const array = ['cinema', 'banana', 'apple'];
const sortedArray = array.sort()

console.log(sortedArray) // ['apple', 'banana', 'cinema']

일반적인 문자로 된 배열 정렬 모습이다. 문자열 첫 글자를 기준 으로 정렬해준다.

오늘 당황했던 건 숫자로 된 배열을 정렬하면서 생김.
아니... sort() 야... 너 문자 정렬이었으면 말을 해줘야지.. 형이 1시간동안 삽질했잖니...

const array = [3, 10, 3, 1, 20]
const sortedArray = array.sort()

console.log(sortedArray) // [1, 10, 2, 20, 3]

문자 정렬처럼 첫 글자를 기준으로 정렬하기 때문에 [1, 2, 3, 10, 20] 이 아니라 [1, 10, 2, 20, 3]가 콘솔에 찍힌다.

명심하자.
숫자 정렬할 때는 sort() 안에 함수 넣어서 정렬하자 !

const array = [3, 10, 3, 1, 20]

console.log(array.sort((a, b) => a-b) // 오름차순 [1, 2, 3, 10, 20]
console.log(array.sort((a, b) => b-a) // 내림차순 [20, 10, 3, 2, 1]

정리

문자 정렬

const array = ['cinema', 'banana', 'apple'];

console.log(array.sort()) // 오름차순 ['apple', 'banana', 'cinema']
console.log(array.reverse()) // 내림차순 ['cinema', 'banana', 'apple']

숫자 정렬

const array = [3, 10, 3, 1, 20]

console.log(array.sort((a, b) => a-b) // 오름차순 [1, 2, 3, 10, 20]
console.log(array.sort((a, b) => b-a) // 내림차순 [20, 10, 3, 2, 1]

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
https://mber.tistory.com/51

profile
Junior FE Developer

0개의 댓글