JavaScript / map(), sort() λ©μλ
π Today I Learned
- map()
- sort()
map()
λ©μλλ λ°°μ΄ λ΄μ λͺ¨λ μμ κ°κ°μ λνμ¬ μ£Όμ΄μ§ ν¨μλ₯Ό νΈμΆν κ²°κ³Όλ₯Ό λͺ¨μ μλ‘μ΄ λ°°μ΄μ λ°ννλ€.const array = [4, 9, 16, 25];
const map = array.map(n => n * 2);
console.log(map);
// expected output: [8, 18, 32, 50]
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt);
console.log(numbers.map(Math.sqrt));
// expected output: [2, 3, 4, 5]
sort()
λ©μλλ λ°°μ΄ λ΄μ μμλ₯Ό μ λ ¬νμ¬ λ°ννλ€.- κ°
0
+ κ°
λ¬Έμ μ λ ¬
const season = ['fall', 'summer', 'spring', 'winter'];
const name = season.sort();
console.log(season.sort());
// expected output: ['fall', 'spring', 'summer', 'winter' ]
μ«μ μ λ ¬
const score = [7, 3, 2, 12, 34, 6];
/* μ€λ₯ */
score.sort();
// expected output: [12, 2, 3, 34, 6, 7]
// ASCII λ¬Έμ μμλ‘ μ λ ¬λμ΄ μ«μμ ν¬κΈ°λλ‘ λμ€μ§ μμ
/* μ μ λμ */
score.sort(function(a, b) { // μ€λ¦μ°¨μ
return a - b;
// expected output: [2, 3, 6, 7, 12, 34]
});
score.sort(function(a, b) { // λ΄λ¦Όμ°¨μ
return b - a;
// expected output: [34, 12, 7, 6, 3, 2]
});