다음과 같은 현금 흐름을 설명하는 두 개의 배열이 있다고 가정합니다. -
const months = ["jan", "feb", "mar", "apr"];
const cashflows = [
{'month':'jan', 'value':10},
{'month':'mar', 'value':20}
]; 우리는 그러한 두 개의 배열을 취하는 JavaScript 함수를 작성해야 합니다. 그런 다음 우리 함수는 각 월에 대한 개체와 해당 월에 대한 현금 흐름 값을 포함하는 결합된 개체 배열을 구성해야 합니다.
따라서 위의 배열의 경우 출력은 다음과 같아야 합니다. -
const output = [
{'month':'jan', 'value':10},
{'month':'feb', 'value':''},
{'month':'mar', 'value':20},
{'month':'apr', 'value':''}
]; 예시
이에 대한 코드는 -
const months = ["jan", "feb", "mar", "apr"];
const cashflows = [
{'month':'jan', 'value':10},
{'month':'mar', 'value':20}
];
const combineArrays = (months = [], cashflows = []) => {
let res = [];
res = months.map(function(month) {
return this[month] || { month: month, value: '' };
}, cashflows.reduce((acc, val) => {
acc[val.month] = val;
return acc;
}, Object.create(null)));
return res;
};
console.log(combineArrays(months, cashflows)); 출력
콘솔의 출력은 -
[
{ month: 'jan', value: 10 },
{ month: 'feb', value: '' },
{ month: 'mar', value: 20 },
{ month: 'apr', value: '' }
]