Array 의 "slice"
function solution(emergency) {
// [...emergency]
let sorted = emergency.slice().sort((a,b)=>b-a);
return emergency.map(v=>sorted.indexOf(v)+1);
}
Object 의 "entries" 이용하여 객체 키:값 바꾸기
const obj = {
1 : "a",
2 : "b",
3 : "c",
}
const swappedObj = Object.entries(obj).reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
console.log(swappedObj);
[결과]
{"a" : 1, "b" : 2, "c" : 3}
팩토리얼
재귀
const fact = (num) => num === 0 ? 1 : num * fact(num - 1);
reduce 이용
const fact = (n) => {
return Array.from({length: n}, (_, i) => i + 1)
.reduce((acc, cur) => acc * cur ,1)
};
경우의 수
n! / ((n-m)! * m!)
function solution(balls, share) {
const fact = (n) => {
return Array.from({length: n}, (_, i) => i + 1)
.reduce((acc, cur) => acc * cur ,1)
}
if(balls === share) return 1;
return Math.round(fact(balls) / (fact(balls - share) * fact(share)));
}
Math 의 "round / ceil / floor"
const num1 = 12.2;
const num2 = 12.7;
console.log(Math.round(num1)); // 12
console.log(Math.ceil(num1)); // 13
console.log(Math.round(num2)); // 13
console.log(Math.floor(num2)); // 12
2 차원 배열 선언
const arr = [];
for (let i = 0; i < 4; i+=1) {
arr[i] = [];
}
console.log(arr); // [[],[],[],[]]
Array 의 "shift() / unshift()"
shift()
let fruits = ["apple", "banana", "cherry"];
let firstFruit = fruits.shift();
console.log(firstFruit); // "apple"
console.log(fruits); // ["banana", "cherry"]
unshift()
let fruits = ["banana", "cherry"];
let newLength = fruits.unshift("apple", "mango");
console.log(newLength); // 4
console.log(fruits); // ["apple", "mango", "banana", "cherry"]