โ ์๋ก ๋ฐฐ์ด ์
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]
'Coding Test' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode - Two Sum (0) | 2021.11.08 |
---|---|
Programmers: ๋ ๊ฐ ๋ฝ์์ ๋ํ๊ธฐ (0) | 2021.08.22 |
Programmers: ํฌ๋ ์ธ ์ธํ๋ฝ๊ธฐ ๊ฒ์ (0) | 2021.08.22 |
Programmers ํด์: ์์ฃผํ์ง ๋ชปํ ์ ์ (0) | 2021.08.22 |
Programmers ์์ ํ์: ๋ชจ์๊ณ ์ฌ (0) | 2021.08.15 |