I want to loop through an array.
Any index which has a length larger than 3 I want to abbreviate.
I want to place the new abbreviated months into a new array.
I want to test that it works by writing the results to the console.
I can get the code to run, however the results don't come out the way I'd hope. From my understanding the loop runs true, running the if statement, which runs true, running the code block. After that the loop should iterate and continue as long as i < months.length, but it doesn't.
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];
for (var i = 0; i < months.length; i++) {
if (months[i].length > 3) {
monthsAbbrev = months[i].slice(0, 3);
}
}
console.log(monthsAbbrev);
You can do it simply with Array.prototype.map()
var months = ["January", "Febuary"]; //sample data for better understanding
var monthsAbbrev = months.map(v => v.substr(0,3));
console.log(monthsAbbrev); //["Jan", "Feb"]
By the way you are not pushing anything into your target array in your code, that is the problem.
Beside the pushing, you can omit the check for length > 3, because slice is already doing it and that prevent to miss some month, like 'May'.
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];
for (var i = 0; i < months.length; i++) {
monthsAbbrev.push(months[i].slice(0, 3));
}
console.log(monthsAbbrev);
You need to add the months to your monthsAbbrev array. One way you can do this is by using the .push() function:
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];
for (var i = 0; i < months.length; i++) {
if (months[i].length > 3) {
monthsAbbrev.push(months[i].slice(0, 3));
}
}
console.log(monthsAbbrev);
You just had to push to the array formed. Rest you already had it.
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];
for (var i = 0; i < months.length; i++) {
if (months[i].length > 3) {
monthsAbbrev.push(months[i].slice(0, 3));
}
}
console.log(monthsAbbrev);
Related
This question already has answers here:
How to get previous month (DECEMBER) name
(6 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I want a function that gives the full name of prev month for any given month[not just current month]
Ex: prevMonth(August) = July; prevMonth(January)= December.
I'm new to js and can't figure out how to use this array to get the result:
monthsarray: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Are expecting a simple solution like this?
var monthsarray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
function prevMonth(curMonth) {
var curMonthIndex = monthsarray.indexOf(curMonth);
var prevMonthIndex;
if (curMonthIndex == 0) prevMonthIndex = monthsarray.length - 1;
else if (curMonthIndex == monthsarray.length - 1) prevMonthIndex = 0;
else prevMonthIndex = curMonthIndex - 1;
return monthsarray[prevMonthIndex];
}
console.log(prevMonth("August"));
console.log(prevMonth("December"));
let monthsarray1= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] ;
let m="May";
console.log(pvsMonth(m))
function pvsMonth(m){
let ln=monthsarray1.length
let idx=monthsarray1.indexOf(m)
if(idx==0){
return monthsarray1[ln-1]
}else{
return monthsarray1[idx-1]
}
}
function prevMonth(month) {
const index = monthsarray.indexOf(month);
if (index > 0) {
return monthsarray[index - 1];
}
if (index === 0) {
return monthsarray[monthsarray.length - 1];
}
throw new Error('Invalid Month given');
}
I am creating dynamic labels for the chart js by supplying range of the month . It is working good if i selected start month and end month in ascending order but it is not working in the case where i selected start month = december and end month = march.
Here is my code ,
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March']; // here i give the lower and upper limit for the label
for (var i = monthNames.indexOf(monthn[0]); i <= monthNames.indexOf(monthn[1]); i++) {
monthArr.push(monthNames[i]);
}
return monthArr;
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March'];
if (monthNames.indexOf(monthn[1]) < monthNames.indexOf(monthn[0])) {
monthNames.unshift(monthNames.splice(monthNames.indexOf(monthn[0]), 1)[0]);
for (var i = monthNames.indexOf(monthn[0]); i <= diff; i++) {
monthArr.push(monthNames[i]);
}
} else {
for (var i = monthNames.indexOf(monthn[0]); i <= monthNames.indexOf(monthn[1]); i++) {
monthArr.push(monthNames[i]);
}
}
return monthArr;
Try to validate the index between the two months
Here is an example with your code and a very small changes.
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthArr = [];
var monthn = ['December','March']; // here i give the lower and upper limit for the label
// make sure that StartMonth is smaller then Endmonth
var startMonth = monthNames.indexOf(monthn[0]) <= monthNames.indexOf(monthn[1]) ? monthNames.indexOf(monthn[0]) : monthNames.indexOf(monthn[1]);
// make sure that EndMonth is bigger then StartMonth
var endMonth = monthNames.indexOf(monthn[0]) <= monthNames.indexOf(monthn[1]) ? monthNames.indexOf(monthn[1]) : monthNames.indexOf(monthn[0]);
for (var i = startMonth; i <= endMonth; i++) {
monthArr.push(monthNames[i]);
}
// Add the missing months
if (startMonth -1 >0)
{
for (var i = 0; i <= startMonth -1; i++) {
monthArr.push(monthNames[i]);
}
}
console.log(monthArr)
I want to change the date format in javaScript and I find this code of "Mike Christensen" that is very nice.
But my question is about what is meaning of use two bracket in javascript array code at var month line 3.
var mydate = new Date(form.startDate.value);
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"] [mydate.getMonth()];
var str = month + ' ' + mydate.getFullYear();
He is indexing the month array using the month number that he gets it from mydate.getMonth()
Here in this code ,mydate.getMonth() is 11 and as is he indexing month array month[11] would be december
var mydate = new Date();
console.log(mydate.getMonth());
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"] [mydate.getMonth()];
console.log(month);
var str = month + ' ' + mydate.getFullYear();
Hope you understand
The first pair of brackets is creating of array, consider it like this
var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
The next pair of brackets is a retrieving operation for the array by index.
someArr[index]
in your case
month[11]
That's it, the author just take an element of the just created array by index, where index is extracted from another variable.
doing this: is a very cheap way to init the var month with only elements in the array declared previously...(something that will save you to write one line more but IMHO decrease the readability of the code... )
so breaking that down:
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"] [mydate.getMonth()];
is the same as
var monthOptionsArray = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var monthIndex = mydate.getMonth();
var monthActual = monthOptionsArray[monthIndex];
Example:
var mydate = new Date();
console.log(mydate.getMonth());
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]; monthI = month[1];
console.log(monthI);
var str = month + ' ' + mydate.getFullYear();
I am trying to get the actual month from a loop. When I step through it in developer tools and month[i] == 4 it doesn't assign actualMonth to checkMonth
Do I have to assign getMonth to month[] and then try and query the value?
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
console.log(month[i]);
if (getMonth == month[i]) {
actualMonth = checkMonth;
}
}
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Too simple?
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = month[getMonth];
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Change your if to if (month[getMonth] == month[i]) {
Do it like this :
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
console.log(month[i]);
if (month[getMonth] == month[i]) { //Compare get month like this
actualMonth = checkMonth;
}
}
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Your problem is that you are comparing an integer and string:
var getMonth = new Date().getMonth(); // This return number from 0 to 11
The code Date().getMonth() returns an integer, and your month list has strings on it
Your code should be:
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = month[getMonth];
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
To get the actual month you only need to access the month list with getMonth as index
slightly Modification required
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
console.log(getMonth);
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
if (getMonth == i) {
actualMonth = checkMonth;
}
}
console.log(actualMonth);
};
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
I'm trying to add a p element containing a single month in this string to a div with the id of "write". How do I get this loop to run through the list of strings and add them to the div?
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"];
var element = document.getElementById("write").innerHTML = months;
for (var i = 0; i <= months; i++) {
var para = document.createElement("p");
var text = document.createTextNode(i);
}
I don't understand why it isn't working. Thanks!
It looks like you're totally misunderstanding how to use arrays, you need to go back to your tutorials and study this.
You need to use months.length as the limit of the array, not just months. You should use <, not <= in the test, because otherwise you'll go past the end of the array. And in the text node you should put months[i], not just i. Then you need to make the text node a child of the paragraph. You can't set the innerHTML of an element to an array; you should be adding the paragraphs as children of the element.
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var element = document.getElementById("write");
for (var i = 0; i < months.length; i++) {
var para = document.createElement("p");
var text = document.createTextNode(months[i]);
para.appendChild(text);
element.appendChild(para);
}
<div id="write"></div>