19

I have a very simple problem but for some reason I can't find the answer for it.

label.forEach(function(value){
    months.push(value['month']);
    revenue.push(value['revenue']);
});

The label is an array of numbers and revenue, in my case this is

[
{month: 9, revenue: 400}, 
{month: 11, revenue: 500},
{month: 12, revenue: 600}
]

This is a forEach loop in javascript, it pushes revenue and a month number into two seperate arrays, the problem is that the month is a number (e.g. 12) but I want the .push() to push a month name instead (December), I can't seem to find anything so I was hoping anyone here could help me out.

Chenmunka
  • 685
  • 4
  • 21
  • 25
peaceduck
  • 231
  • 1
  • 2
  • 9

5 Answers5

22
var months = [ "January", "February", "March", "April", "May", "June", 
           "July", "August", "September", "October", "November", "December" ];

var selectedMonthName = months[value['month']];

look at the links

stack 1

Oğuz
  • 344
  • 2
  • 10
  • Totally looked over this anwer but it worked, thanks a lot! – peaceduck Apr 19 '18 at 08:12
  • 3
    If the months start from 1 (January is 1) you would have to access the month like this `var selectedMonthName = months[value['month'] - 1];` because January is at index 0 – abrull Apr 30 '20 at 00:00
  • I am using this with a blank string at index zero. Defensive coding would make me test for a month with value 0 – Manuel Hernandez Jul 06 '21 at 19:22
12
Intl.DateTimeFormat('en', { month: 'long' }).format(new Date('1')); // January

Can be achieved using Internationalization API

praisegeek
  • 421
  • 4
  • 6
Viktor Gusev
  • 555
  • 3
  • 12
7

This can be easily done using moment.js.

var months = [];
months.push(moment().month(0).format("MMMM"));
console.log(months);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
1

another simple way of doing it is with a map, create one like this

const monthNumberToLabelMap = {
  [1]: 'January',
  [2]: 'February',
  [3]: 'March',
  [4]: 'April',
  [5]: 'May',
  [6]: 'June',
  [7]: 'July',
  [8]: 'August',
  [9]: 'September',
  [10]: 'October',
  [11]: 'November',
  [12]: 'December',
}

then use the map in your code like this

label.forEach(function(value){
    months.push(monthNumberToLabelMap[value['month']]);
    revenue.push(value['revenue']);
});

note:

it wasn't clear from your question what the format of your month data is, default javascript months are 0-11 in which case you would have change my map

john mason
  • 159
  • 2
  • 5
0
    <script src="https://momentjs.com/downloads/moment.min.js"></script>

    var monthNumber='03';
    var month = [ "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December" ];
    var monthIndex = moment().month(monthNumber[1]-1).format("M");
    var selectedMonthName = month[monthIndex-1];
    alert(selectedMonthName);