Backend/JavaScript,NodeJS, Express
[javaScript] 자료구조, 이차원 배열, 이차원 Object
jellylucy
2023. 4. 18. 22:53
arr.reduce(callback[, initialValue]) : 원하는 값들을 하나씩 더하기 값 만드는 것
배열을 축소하거나
새로운 객체를 생성하거나 수정하는 작업에 적합
일차원 배열을 원하는 조건에 따라 이차원 배열로 만들고자 할 때.
const array1 = [1,2,3,4];
// reduce(콜백함수, 초기인자)
// 리듀서의 결과값은 하나의 value
const initial = 0; //초기인자
const result = array1.reduce((arr, cur) => arr+cur, 0)
console.log(result) // 10
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const result = arr.reduce((acc, cur) => {
if (cur % 2 === 0) {
if (!acc.length || acc[acc.length - 1].length === 2) {
acc.push([cur]);
} else {
acc[acc.length - 1].push(cur);
}
}
return acc;
}, []);
console.log(result); // [[2, 4], [6, 8]]
arr.map(callback(currentValue[, index[, array]])[, thisArg]) : 모든 배열원소 개수만큼 순서대로 불러 함수의 반환값으로 새로운 배열
map은 callback 함수를 각각의 요소에 대해 한번씩 순서대로 불러 그 함수의 반환값으로 새로운 배열을 만듭니다. callback 함수는 (undefined도 포함해서) 배열 값이 들어있는 인덱스에 대해서만 호출됩니다. 즉, 값이 삭제되거나 아직 값이 할당/정의되지 않은 인덱스에 대해서는 호출되지 않습니다.
array1 = [1,2,3,4];
const newArr = array1.map(x => x%2 === 0)
console.log(newArr); //[true, false, true, false]
// 이차원 배열인 경우
const appliedItems = itemsData.map(item => {
item.productOptions = item.productOptions.map(po => {
const row = worksheetRows.find(row => row['key'] === po.key);
const isExistSpecialDiscountBasePrice = worksheetRows.find(row => row['key'] === po.key && row['3단 꺾기 활성화'] === 'Y' && row['기본행사가']);
if (row) {
po.discountValue = row['할인'];
if (isExistSpecialDiscountBasePrice) {
po.specialDiscountBasePrice = row['행사가'];
}
}
return po;
});
return item;
});
arr.filter(callback(element[, index[, array]])[, thisArg]) : 테스트 통과한 요소들로 구성되는 새로운 배열
array1 = [1,2,3,4];
const newArr = array1.filter(x => x%2 === 0)
console.log(newArr); //[2,4]