Home > database >  Adding conditional statement to Array.from()
Adding conditional statement to Array.from()

Time:04-09

I have the following code,

AllDays= Array.from(moment.range(startDate, endDate).by('day')).map(day => day.format('YYYY-MM-DD'));

I would like to add a conditional to it so if a given day in the range start - end is chosen it is NOT included in the generated array.

So say the range is 1st-4th, I would like to specify if its the 3rd do not include it in the array.

I can do this by looping over the array AFTERWARDS and removing the dates but was wondering if there was a way to do it from within ?

CodePudding user response:

Just slice the elements from 0 to length - 1:

this['moment-range'].extendMoment(moment);

let startDate = '2022-04-01';
let endDate = '2022-04-04';

let allDays = Array.from(moment.range(startDate, endDate).by('day')).map(day => day.format('YYYY-MM-DD')).slice(0,-1);

console.log(allDays /* except the last */);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.2/moment-range.js"></script>

CodePudding user response:

const datesToRemove = new Set(ArrayOfDatesToRemove);
AllDays = AllDays.filter(date => !datesToRemove.has(date));

I was able to solve this using filter

  • Related