Month Array in JavaScript Not Pretty

Viewed 81105

How can i make it nicer?

var month = new Array();

month['01']='Jan';
month['02']='Feb';
month['03']='Mar';

etc. Itd be nice to do it like:

var months = new Array(['01','Jan'],['02','Feb'],['03','Mar']);

For example. anyway like that to simplify it?

9 Answers

Short Dynamic Solution:

Here's a dynamic solution that does not require hard-coding an array of months:

const month = f=>Array.from(Array(12),(e,i)=>new Date(25e8*++i).toLocaleString('en-US',{month:f}));

Test Cases:

// Using Number Index:

month`long`[0];    // January
month`long`[1];    // February
month`long`[2];    // March

month`short`[0];   // Jan
month`short`[1];   // Feb
month`short`[2];   // Mar

month`narrow`[0];  // J
month`narrow`[1];  // F
month`narrow`[2];  // M

month`numeric`[0]; // 1
month`numeric`[1]; // 2
month`numeric`[2]; // 3

month`2-digit`[0]; // 01
month`2-digit`[1]; // 02
month`2-digit`[2]; // 03

// Using String Index:

let index_string = '01';

month`long`[index_string-1];    // January
month`short`[index_string-1];   // Jan
month`narrow`[index_string-1];  // J
month`numeric`[index_string-1]; // 1
month`2-digit`[index_string-1]; // 01

Months in javascript for faster access O(1)

const months = { "01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct",

"11": "Nov",

"12": "Dec", };

Related