-1

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.

MTCoster
  • 5,868
  • 3
  • 28
  • 49
Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • 1
    Change Array(7) to Array.from(Array(7)) – Alex G Nov 17 '18 at 10:55
  • what are you `map`ping on? `Array(7)` is empty – Andrea Nov 17 '18 at 10:57
  • Array(7) is not an empty array, just an array with 7 empty elements. I just thought that I can get the index by mapping on them. But not. Anyways, thanks @AlexG, very good solution. – Gergő Horváth Nov 17 '18 at 11:00
  • Possible duplicate of [Is a new JavaScript array with length unusable?](https://stackoverflow.com/questions/28371449/is-a-new-javascript-array-with-length-unusable) – jonrsharpe Nov 17 '18 at 11:39

2 Answers2

3

Simplest way is to use combination of array.from and new array like so:

Array.from(new Array(5), (und, ind) => ind) // This returns [0,1,2,3,4] 

und is undefined since the array is initiated with undefined values and needs to be filled. So you can extend this with more complex evaluating :

Array.from(new Array(5), (und, ind) => {return some_data_based_on_ind})

There is also Array.fill method for simple fills:

Array(6).fill('somedata')
Goran.it
  • 5,991
  • 2
  • 23
  • 25
0

Just push into your data variable. I have used something similar using date-fns instead of moment

const daysOfWeek = () => {
   const days = []
   let startDate = dateFns.startOfWeek(new Date())

   for (let i = 0; i < 7; i++) {
       days.push(
            <span key={i}>
               { dateFns.format(dateFns.addDays(startDate, i), 'dddd') }
            </span>
        )
    }

    return days
}
Jason McFarlane
  • 2,048
  • 3
  • 18
  • 30