It’s a month that I don’t write anything because my busyness almost drive me crazy. Today there is a small demand to creat a continuous array of natural numbers that it’s items are all less than current hour. I think it a good idea to write it down.

It’s easy to generate a array starts from 0 and contains n consecutive natural numbers by using for:

1
2
3
4
5
let arr = [];
for (let i = 0; i < n; i++) {
arr.push(i);
}
return arr;

But the code is too long for me. After checking the documentation, I noticed the interface Array.from can do the same thing and SHORTER.

1
Array.from({ length: n }, (item, idx) => idx);

Fixed in ONE line.

The idea is using Array to generate the very length array, then we take item’s index as final result.

Fist of all, we use Array.form({ length: n }) to create a array which length is n, items are all undefined. Then we pass a function to the interface’s second parameter which is a map function, now we can get the item’s index.

After getting the array, the last part is simple:

1
2
3
4
let now = new Date();
return Array.from({ length: 24 }, (item, idx) => idx).filter(hour => {
return hour < now.getHours();
});

EOF.