본문으둜 κ±΄λ„ˆλ›°κΈ°

πŸ“„ Sort Array

Question Description​

숫자둜 이루어진 배열이 μ£Όμ–΄μ‘Œμ„ λ•Œ, sort ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ 배열을 μ •λ ¬ν•˜μ„Έμš”. λ‹€μŒ 두 κ°€μ§€ κ²½μš°μ— λŒ€ν•œ ν•΄κ²° 방법을 μ œμ‹œν•˜μ„Έμš”:

  1. μž‘μ€ 것뢀터 큰 것 순으둜 μ •λ ¬(μ˜€λ¦„μ°¨μˆœ)
  2. 큰 것뢀터 μž‘μ€ 것 순으둜 μ •λ ¬(λ‚΄λ¦Όμ°¨μˆœ)

μ˜€λ¦„μ°¨μˆœ 정렬​

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 },
];