๐ Sort Array
Question Descriptionโ
์ซ์๋ก ์ด๋ฃจ์ด์ง ๋ฐฐ์ด์ด ์ฃผ์ด์ก์ ๋, sort ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐฐ์ด์ ์ ๋ ฌํ์ธ์. ๋ค์ ๋ ๊ฐ์ง ๊ฒฝ์ฐ์ ๋ํ ํด๊ฒฐ ๋ฐฉ๋ฒ์ ์ ์ํ์ธ์:
- ์์ ๊ฒ๋ถํฐ ํฐ ๊ฒ ์์ผ๋ก ์ ๋ ฌ(์ค๋ฆ์ฐจ์)
- ํฐ ๊ฒ๋ถํฐ ์์ ๊ฒ ์์ผ๋ก ์ ๋ ฌ(๋ด๋ฆผ์ฐจ์)
์ค๋ฆ์ฐจ์ ์ ๋ ฌโ
const numbers = [10, 5, 50, 2, 200];
// ๋น๊ต ํจ์ ์ฌ์ฉ
numbers.sort(function (a, b) {
return a - b;
});
console.log(numbers); // [2, 5, 10, 50, 200]
๋ด๋ฆผ์ฐจ์ ์ ๋ ฌโ
const numbers = [10, 5, 50, 2, 200];
numbers.sort(function (a, b) {
return b - a;
});
console.log(numbers); // [200, 50, 10, 5, 2]
์๋์ ์ผ๋ก string ์ฝ์ โ
const mixedNumbers = [10, '5', 50, '2', 200];
mixedNumbers.sort(function (a, b) {
return Number(a) - Number(b);
});
console.log(mixedNumbers); // ['2', '5', 10, 50, 200]
ํ์ง๋ง ์ด ํด๊ฒฐ ๋ฐฉ๋ฒ์ ์ซ์๋ก ๋ณํํ ์ ์๋ ๋ฌธ์์ด(์: 'iphone', 'ipad')์ ์ ์ธํ ์ ์์ต๋๋ค. ์ด๋ฌํ ๋ฌธ์์ด์ NaN์ผ๋ก ๋ณํ๋๋ฉฐ, ์ ๋ ฌ ๊ฒฐ๊ณผ์์ ๋ง์ง๋ง์ ์ฌ ์๋ ์์ง๋ง ๋ธ๋ผ์ฐ์ ์ ๋ฐ๋ผ ๋ค๋ฅธ ๊ฒฐ๊ณผ๊ฐ ๋์ฌ ์ ์์ต๋๋ค. ์ด๋ฐ ๊ฒฝ์ฐ์๋ filter๋ฅผ ์ฌ์ฉํ์ฌ ๋จผ์ ์ ์ธํ ํ ๋ฐฐ์ด์ ์ฌ๊ตฌ์ฑํ๋ ๊ฒ์ ๊ณ ๋ คํด์ผ ํฉ๋๋ค.
Object ์ ๋ ฌโ
const mockArray = [
{ type: 'a', label: 1 },
{ type: 'a', label: 2 },
{ type: 'c', label: 1 },
{ type: 'c', label: 3 },
{ type: 'b', label: 2 },
];