Loop through an array and print a specific range of values? - javascript

var months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October","November", "December"];
// For Loop
for (var i = 0; i = months.slice(4, 8); i++) {
alert(a);
I'm trying to loop through this array and alert the values in a specific range, May - August. I can't seem to figure this out. Thanks!

For a for loop, specify your start index (May = 4) and end index (August = 7), and use this pattern:
var months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October","November", "December"];
// For Loop
for (var i = 4; i <= 7; i++) {
alert(months[i]);
}

If you just want those items, and you know the contents of the array, you have a few options:
var months = ["January", "February", "March", "April",
"May", "June", "July","August", "September",
"October","November", "December"];
// For Loop
for (var i = 4; i <= 7; i++) {
alert(months[i]);
}
There's no need to slice while using the for loop. You already know which indices you're interested in, so you can just iterate across that range. It's also the most efficient of these choices, generally.
// Slice and for-loop
var selected = months.slice(4,7);
for (var i = 0; i < selected.length; i++) {
alert(selected[i]);
}
You could slice first and then iterate across the whole (new) array in a for loop. Generally, you wouldn't do this. However, if your conditions for narrowing the array were more complex, there might be reasons to build the array out first and then loop over it, so here's a clean example of how to do that.
// Slice and forEach
months.slice(4,7).forEach(function(x) {alert(x);});
This would be my personal choice, because it's concise. It's effectively the same as the slice-and-loop example (slightly less performant, but not in a way you're ever likely to need to care about), just expressed using Array.prototype.forEach() instead of a separate for loop.

You need to store the sliced array in a temporary variable and loop over that.
Example: https://jsfiddle.net/epkkstqz/1/
var months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October","November", "December"];
for (var i = 0, slice = months.slice(4, 8); i < slice.length; i++) {
alert(slice[i]);
}

Related

How to increment textbox (month)name on button click in javascript

I want to increase and decrease a text box name on click button
here an image i post to give clarification of what i have to do exactly
i tried but text value increaseing but i wana show month name in that text box
Any help is appreciated.
You could try with Array .create the array for month .And apply the increment and decrements value with array arguments position.Ternary operator used for restrict the count below 0 and above 11
var month = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var c =0;
$('#mins').click(function(){
c = c-- > 0 ? c-- : 0;
$('#mnt').val(month[c])
})
$('#plus').click(function(){
c = c++ < 11 ? c++ : 11;
$('#mnt').val(month[c])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="mnt" value="January">
<button id="mins">-</button>
<button id="plus">+</button>
Create an Array of month names, a starting variable to represent the current location in the Array, and a variable to hold the input field for the Month:
var months = ["January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"];
var currentMonth = 0;
var monthInput = $("#month-input");
Now add click events to the + and - buttons. You'll need to add an id attribute to each one.
$("#subtract-month-button").click(subtractMonth);
$("#add-month-button").click(addMonth);
Finally, your methods to handle the click events.
function subtractMonth () {
if (currentMonth > 0) {
currentMonth--;
}
monthInput.val(months[currentMonth]);
}
function addMonth () {
if (currentMonth < months.length - 1) {
currentMonth++;
}
monthInput.val(months[currentMonth]);
}

Results from loop don't work correctly

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);

Looping through an array to div?

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>

How to check if a string is a substring of any element in an array

I have an array
var months = ["January", "February", "March", "April", \
"May", "June", "July", "August", "September", "October", \
"November", "December"];
I have strings like "Nov", "October", "Jun", "June", "Sept", "Sep" etc. The point is, the string can be a substring of one of the months.
What is the best way to compare the string to be a substring of the array elements? How do I find out the index of the month?
I am looking at javascript/jQuery.
I know I can just loop through the array checking against each element using search and break when found. I want something better.
var month_index = function(target) {
target = target.toLocaleLowerCase();
return jQuery.inArray(true, jQuery.map(months, function(s) {
return s.toLocaleLowerCase().indexOf(target) > -1;
}))
};
var index_of_october = month_index("oct");
var substr = 'nov', months = ["december", "november", "feb"];
var index = months.indexOf( months.filter(function(v){ return v.indexOf(substr) >= 0;})[0]);
alert(index)
http://jsfiddle.net/KeMe9/
Put your array items in lower case
var txt = "Sep";
var found = false;
txt = txt.toLowerCase();
for (var i = 0; i < 12; i++) {
if (months[i].indexOf(txt) > -1) {
found = true;
break;
}
}

chartjs custom y axis values, different text for each one

I am trying to change numeric values within y axis with custom text ones. I tried using loop but it takes only the first one.
callback:function(value) {
var value = ["January", "February", "March", "April", "May"];
for(i = 0; i < value.length; i++){
return value[i];
}
}
here is FIDDLE with the sample graph
maybe case of something ?
Try to return value from the array properly,
callback:function(value) {
var x = ["January", "February", "March", "April", "May", "June", "July"];
return x[value | 0];
}
DEMO

Categories

Resources