1๏ธโฃ sort() ํจ์ ์ฌ์ฉ
arr.sort([compareFunction])
compareFunction : ์ ๋ ฌ ์์๋ฅผ ์ ์ํ๋ ํจ์
์ด ๊ฐ์ด ์๋ต๋ ๊ฒฝ์ฐ ๋ฐฐ์ด์ ์์๊ฐ ๋ฌธ์์ด๋ก ์ทจ๊ธ๋์ด ์ ๋์ฝ๋ ๊ฐ ์์๋๋ก ์ ๋ ฌ๋๋ค.
ex. [1, 2, 3, 12, 23] โก๏ธ [1, 12, 2, 23, 3]
* ์ฌ์ฉ ์ ์๋ณธ ๋ฐฐ์ด ์์ฒด๊ฐ ๋ณ๊ฒฝ๋๋ค.
arr = ['oh', 'My', 'b', 'Boy'];
arr.sort();
//Boy, My, b, oh
2๏ธโฃ ๋น๊ต ์ฐ์ฐ์ ์ฌ์ฉํ๊ธฐ
์๋ฐ์คํฌ๋ฆฝํธ์์๋ ๋น๊ต์ฐ์ฐ์๋ฅผ ์ด์ฉํ์ฌ ๋ฌธ์์ด์ ๋น๊ตํ ์ ์๋ค.
//์ค๋ฆ์ฐจ์
arr.sort((a, b) => a > b ? 1 : -1);
//๋ด๋ฆผ์ฐจ์
arr.sort((a, b) => a > b ? -1 : 1);
3๏ธโฃ localeCampare() ๋ฉ์๋
๋ฌธ์์ด์ ์ฌ์ ์ ์์์์ ํด๋น ๋ฌธ์๊ฐ ์์ ์๋์ง, ๋ค์ ์๋์ง, ๊ฐ์์ง ํ๋จํ์ฌ -1, 1, 0์ ๋ฐํ ๊ฐ์ ์ฃผ๋ ๋ฉ์๋
'a'.localeCompare('c');
//-1
let str = ['a', 'z', 'c', 'y'];
str.sort((a, b) => a.localeCompare(b));
//['a', 'c', 'y', 'z']
// ์ค๋ฆ์ฐจ์
arr.sort((a, b) ⇒ a.localeCompare(b));
// ๋ด๋ฆผ์ฐจ์
arr.sort((a, b) ⇒ b.localeCompare(a));
4๏ธโฃ ํน์ ๊ฐ ์ ๋ ฌ ๊ธฐ์ค ๋ง๋ค๊ธฐ
ํน์ ํ ์ ๋ ฌ์ ๊ธฐ์ค์ ๋ง๋ค์ด์ ์ ๋ ฌํ ์ ์๋ค.
//์ ๋ ฌ ๊ธฐ์ค
const orderBy = ['ํ์ฅ', '์ฌ์ฅ', '๋ถ์ฅ', '๊ณผ์ฅ', '์ฌ์'];
const data = ['์ฌ์ฅ', '์ฌ์', 'ํ์ฅ', '๋ถ์ฅ', '๊ณผ์ฅ', '์ฌ์'];
data.sort((a, b) => orderBy.indexOf(a) - orderBy.indexOf(b));
1๏ธโฃ ์ซ์ ์ ๋ ฌํ๊ธฐ
1๏ธโฃ-1๏ธโฃ ์ซ์ ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ๊ธฐ
arr.sort(function(a, b) {
return a - b;
});
arr.sort((a, b) => a - b);
1๏ธโฃ-2๏ธโฃ ์ซ์ ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌํ๊ธฐ
arr.sort(function (a, b) {
return b - a;
});
arr.sort((a, b) => b - a);
2๏ธโฃ ๋ฌธ์ ์ ๋ ฌํ๊ธฐ
2๏ธโฃ-1๏ธโฃ ๋ฌธ์ ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ๊ธฐ
arr = ['oh', 'My', 'b', 'Boy'];
arr.sort();
//Boy, My, b, oh
2๏ธโฃ-2๏ธโฃ ๋ฌธ์ ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌํ๊ธฐ
arr = ['oh', 'My', 'b', 'Boy'];
arr.sort(function(a, b) {
if (a < b) return 1;
if (a > b) return -1;
if (a === b) return 0;
});
//oh, b, My, Boy
* ๋์๋ฌธ์ ๊ตฌ๋ถ ์์ด ์ค๋ฆ์ฐจ์/๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌํ๊ธฐ ์ํด์๋
๋ฌธ์์ด ๋น๊ต ์ ๋ชจ๋ ๋๋ฌธ์/์๋ฌธ์๋ก ๋ณํํ์ฌ ๋น๊ตํด์ผ ํ๋ค.
[Javascript] ๋ฌธ์์ด ๋์๋ฌธ์ ๋ณ๊ฒฝ (toUpperCase(), toLowerCase()
2๏ธโฃ-3๏ธโฃ ๋ฌธ์ ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ๊ธฐ (๋์๋ฌธ์ ๊ตฌ๋ถ x)
const arr = ['oh', 'My', 'b', 'Boy'];
arr.sort(function(a, b) {
let upperA = a.toUpperCase();
ler upperB = b.toUpperCase();
if (upperA > upperB) return 1;
if (upperA < upperB) return -1;
if (upperA === upperB) return 0;
});
//b, Boy, My, oh
2๏ธโฃ-4๏ธโฃ ๋ฌธ์ ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌํ๊ธฐ (๋์๋ฌธ์ ๊ตฌ๋ถ x)
const arr = ['oh', 'My', 'b', 'Boy'];
arr.sort(function(a, b) {
let upperA = a.toUpperCase();
ler upperB = b.toUpperCase();
if (upperA > upperB) return -1;
if (upperA < upperB) return 1;
if (upperA === upperB) return 0;
});
//oh, My, Boy, b
3๏ธโฃ๊ฐ์ฒด ์ ๋ ฌํ๊ธฐ
์ ๋ ฌ ์ํค๋ ๊ธฐ์ค์ ๊ฐ์ฒด์ value ๊ฐ์ผ๋ก ์ก์์ ๋น๊ตํ๋ค.
const data = [
{ name: 'cherry', color: "๋นจ๊ฐ์" },
{ name: 'banana', color: "๋
ธ๋์" },
{ name: 'orange', color: "์ฃผํฉ์" }
];
//sortํจ์
data.sort(function(a, b) {
return a.name - b.name;
});
// ๋น๊ต์ฐ์ฐ์
[...data].sort((a, b) => a.name > b.name ? 1 : -1);
// localeCompare ๋ฉ์๋
[...data].sort((a, b) => a.name.localeCompare(b.name));