이론
배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환해요.
arr.reduce(callback[, initialValue]);
callback 함수는 네 개의 인자를 가져요.
accumulator (acc, prev) : 콜백의 반환값을 누적
currentValue (cur, curr) : 처리할 현재 요소
currentIndex (idx, index) : 처리할 현재 요소의 인덱스 (optional)
array (src) : reduce()를 호출한 배열 (optional)
initialValue를 제공한 경우, acc는 initialValue와 같고, cur는 배열의 첫 번째 요소와 같아요.
initialValue를 제공하지 않은 경우, acc는 배열의 첫 번째 요소와 같고, cur는 두 번째 요소와 같아요.
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((prev, curr) => prev + curr, 0);
console.log(sum); // 15
map vs reduce
map()은 반환값이 같은 길이의 배열이고, reduce()는 반환값이 무엇이든 상관없어요.
주어진 조건에 따라 map()과 reduce() 또는 다른 메서드를 사용해야 해요.
slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환해요. 원본 배열은 바뀌지 않아요.
arr.slice([begin[, end]])
begin 또는 end 가 음수인 경우, 배열의 끝에서부터의 길이를 나타내요.
begin 이 생략된 경우, 0 번째 인덱스부터 추출해요.
end 가 생략된 경우, 배열의 끝까지 추출해요.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
코드
function solution(arr, query) {
return query.reduce((acc, cur, idx) => {
if (idx % 2 === 0) {
return acc.slice(0, cur + 1);
} else {
return acc.slice(cur);
}
}, arr);
}