I need to create an array, and it's elements just depending on the index. To make sense about my current problem, I want to return the dates of a selected day's week.
// With for
const getWeekDatesFor = day => {
const dayIndex = moment(day).format('E') - 1;
const dates = [];
for(let i = 0; i < 7; i++){
if(i < dayIndex){
const lessWith = dayIndex - i;
dates[i] = moment(day).subtract(lessWith, "d").format('YYYY-M-D')
} else {
const moreWith = i - dayIndex;
dates[i] = moment(day).add(moreWith, "d").format('YYYY-M-D')
}
}
return dates
}
// How I wanted to simplify (but returns empty array with 7 elements)
const getWeekDatesNew = day => {
const dayIndex = moment(day).format('E') - 1;
return Array(7).map((e, i) => {
if(i < dayIndex){
const lessWith = dayIndex - i;
return moment(day).subtract(lessWith, "d").format('YYYY-M-D')
} else {
const moreWith = i - dayIndex;
return moment(day).add(moreWith, "d").format('YYYY-M-D')
}
})
}
For loops are good, but I'm sure that with ES6 we have a simpler way to perform these actions: create an array where items depending on it's index. All I want to know what is the ES6 method of doing this.