I have next two arrays:
JavaScript
x
3
1
const firstArray = [{startDate: 5, number: 15}, {startDate: 25, number: 10}, {startDate: 26, number: 10}];
2
const secondArray= [{startDay: 2, endDay:10, number: 15}, {startDay: 20, endDay:30, number: 20}];
3
if startDate
is between startDay
and endDay
, I have to minus firstArray number
and secondArray number
creating new key with result
As result, I have to put new key in firstArray with result:
JavaScript
1
2
1
const firstArray = [{startDate: 5, number: 15, result: 0}, {startDate: 25, number: 25, result: -10}, {startDate: 26, number: 25, result: 0}];
2
if I have more than one startDate in the same range(between startDay and endDay) I have to add to the last result of that range
The code I have for now:
JavaScript
1
2
1
firstArray.map(el => ({el, result: el.number - here's number from the secondArray according to the requirements}))
2
Advertisement
Answer
Map won’t work too well for looping through two arrays and changing values.
Just use a simple for
loop, check your conditions between firstArray[i]
and secondArray[i]
, then add the value to firstArray[i].result
JavaScript
1
8
1
const firstArray = [{startDate: 5, number: 15}, {startDate: 25, number: 20}];
2
const secondArray= [{startDay: 2, endDay:10, number: 10}, {startDay: 20, endDay:30, number: 20}];
3
4
for (let i = 0; i < Math.min(firstArray.length, secondArray.length); i++)
5
if (secondArray[i].startDay < firstArray[i].startDate && firstArray[i].startDate < secondArray[i].endDay)
6
firstArray[i].result = firstArray[i].number - secondArray[i].number;
7
8
console.log(firstArray);