get previous years in array using momentjs
Asked Answered
M

2

6

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) { // }

Monasticism answered 28/9, 2018 at 3:50 Comment(1)
You don't really need moment.js for thisDisposal
E
12

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));
Epact answered 28/9, 2018 at 4:2 Comment(4)
Another option for the return value: return Array.from({ length: back }, (v, i) => year - back + i + 1);Disposal
@RobertMennell I like that. Never thought of that approach.Epact
Array.from() has a nice footprint that makes this sort of thing REALLY smoothDisposal
@RobertMennell Yeah, I agree. Updated my answer. Thanks for the suggestion.Epact
C
0

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))
Chunchung answered 21/11, 2022 at 11:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.