Swanzi Swanzi - 10 months ago 46
Javascript Question

Increase each integer by one return the Javascript array

I'm new to learning javascript and currently doing a free online mini-bootcamp before I start a more serious program. The mini-camp offered some exercises to practice what was taught during the video. I've watched the video multiple times trying to track down a clue as to what I'm doing wrong here and I've tried Googling the issue but I can't seem to turn anything up. I have very limited knowledge on how this all works, and I think I just need someone who knows what they're doing to explain it to me.

Here is the exercise, with the instructions commented just below:

function incrementByOne(arr) {


// arr is an array of integers

// increase each integer by one
// return the array

And here is my attempt at solving:

function incrementByOne(arr) {
for (var i = 0; i < arr; i++) {
return (arr[i]);
}


When I cross check my solution with the provided test it fails every time. I think the problem lies in my lack of understanding on how to properly return the array? I'm not sure, hopefully that's where you come in!

Answer Source

There are several issues:

for (var i = 0; i < arr; i++) {
  // ...
}

The for loop will stop as soon as the condition evaluates to false. Because you want to loop over every array item, you have to compare i to the length of the array, which is arr.length:

for (var i = 0; i < arr.length; i++) {
  // ...
}

The code inside the for loop is now executed for each element. Increment the ith element:

for (var i = 0; i < arr.length; i++) {
  arr[i]++; // increment it by one
}

Now, your array contains the updated values. Return a reference to the array:

function incrementByOne(arr) {
  for (var i = 0; i < arr.length; i++) {
    arr[i]++; // increment it by one
  }
  return arr;
}

If you can create a new array:

function incrementByOne(arr) {
  return arr.map(item => item + 1);
}
// or:
var incrementByOne = arr => arr.map(i => i + 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download