koalaok
koalaok

Reputation: 5720

How can I fill an array with a callback func result in javascript?

Let's say I have something like this:

window.dayNames = function () {
 let names = [];
 for (let i = 0; i < 7; i++) {
    names.push(moment().day(i).format('dddd'));
 }
 return names;
}

Is there a cleaner shorthand to have it with js? e.g. I was looking at lodash lib _.fill

I was wondering if exists Something like:

 _.fill(0,7, (i) => {return moment().day(i).format('dddd');}); 

Upvotes: 3

Views: 2075

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

You can use lodash's _.times():

const dayNames = (n = 7) => _.times(n, i => moment().day(i).format('dddd'));

const result = dayNames();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Upvotes: 3

CD..
CD..

Reputation: 74096

You can use Array.from:

Array.from({length:7}, (_, i) => moment().day(i).format('dddd'))

Array.from() has an optional parameter mapFn, which allows you to execute a map function on each element of the array

Upvotes: 12

Related Questions