How can I generate a list of array till today? I can't hardcode [2016,2017,2018]
, because I have to do it every year.
function (numberOfYearsBack) { // }
How can I generate a list of array till today? I can't hardcode [2016,2017,2018]
, because I have to do it every year.
function (numberOfYearsBack) { // }
Get the current year using getFullYear()
, and use Array.from()
with a map function to declare and initialize an array with the values you need:
const years = (back) => {
const year = new Date().getFullYear();
return Array.from({length: back}, (v, i) => year - back + i + 1);
}
console.log(years(3));
return Array.from({ length: back }, (v, i) => year - back + i + 1);
–
Disposal Array.from()
has a nice footprint that makes this sort of thing REALLY smooth –
Disposal function years(count, startYear){
const yearList = [];
const year = startYear || new Date().getFullYear();
for(let i = 0; i < count; i+=1 ){
yearList.push(Number(year)-i)
}
return yearList.sort((a,b)=>a-b)
}
console.log(years(10, 2022))
© 2022 - 2024 — McMap. All rights reserved.
moment.js
for this – Disposal