HeresJohnny5
HeresJohnny5

Reputation: 71

Results from loop don't work correctly

  1. I want to loop through an array.
  2. Any index which has a length larger than 3 I want to abbreviate.
  3. I want to place the new abbreviated months into a new array.
  4. 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);

Upvotes: 1

Views: 49

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386578

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

Upvotes: 1

Ayan
Ayan

Reputation: 2380

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

Upvotes: 1

j08691
j08691

Reputation: 207901

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

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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.

Upvotes: 4

Related Questions