Reputation: 5720
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
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
Reputation: 74096
You can use Array.from
:
Array.from({length:7}, (_, i) => moment().day(i).format('dddd'))
Array.from()
has an optional parametermapFn
, which allows you to execute a map function on each element of the array
Upvotes: 12