Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get previous years in array using momentjs

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

like image 793
Melissa94 Avatar asked Sep 28 '18 03:09

Melissa94


1 Answers

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));
like image 69
Robby Cornelissen Avatar answered Oct 10 '22 21:10

Robby Cornelissen