Programmers ์ •๋ ฌ: K๋ฒˆ์งธ์ˆ˜

โœ… ์ƒˆ๋กœ ๋ฐฐ์šด ์ 

sort๋Š” ๋ฌธ์ž์—ด์„ ์ •๋ ฌํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ˆซ์žํ˜•์œผ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.

์ˆซ์ž ํฌ๊ธฐ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๊ณ  ์‹ถ์„ ๋•Œ๋Š” compareFunction์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

compareFunction์€ ์ •๋ ฌ ๊ธฐ์ค€์„ ์ •์˜ํ•ด์„œ ์ •๋ ฌํ•ด์ค๋‹ˆ๋‹ค.

 

 

์ฐธ๊ณ  MDN Array.prototype.sort()

 

Array.prototype.sort() - JavaScript | MDN

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

developer.mozilla.org

 

 

ํŠน์ • ๊ธฐ์ค€์— ์˜ํ•ด ๊ณ„์‚ฐ๋œ ๊ฐ’์ด 0๋ณด๋‹ค ํฌ๋ฉด ์ˆœ์„œ๋ฅผ ๋ฐ”๊ฟ”์ฃผ๊ณ ,
ํŠน์ • ๊ธฐ์ค€์— ์˜ํ•ด ๊ณ„์‚ฐ๋œ ๊ฐ’์ด 0๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด ์ˆœ์„œ๋ฅผ ๊ทธ๋Œ€๋กœ ์œ ์ง€ํ•ฉ๋‹ˆ๋‹ค.
์ด๋ ‡๊ฒŒ ํ•จ์œผ๋กœ์จ ์ˆซ์ž ํฌ๊ธฐ์— ๋”ฐ๋ผ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์ด ๊ฐ€๋Šฅํ•ด์ง‘๋‹ˆ๋‹ค.

 

 

If compareFunction(a, b) returns a value > than 0, sort b before a.
If compareFunction(a, b) returns a value ≤ 0, leave a and b in the same order.

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);

// [1, 2, 3, 4, 5]