-5

You are given an array of five numbers called increaseByTwo. Use a for loop to iterate through the array and increase each number by two.

const increaseByTwo = [1,2,3,4,5];

I need the result to be [3,4,5,6,7]

I'm not sure how to add +2 to the array itself, or any operator.

I've currently tried

const increaseByTwo = [1,2,3,4,5];
for (let i=0, i<increaseByTwo.length, i++)
console.log (increaseByTwo + 2) 

Results turn out to be but 3 4 5 6 7

on each seperate line, but need it to do be on one [3,4,5,6,7]

4

5 Answers 5

1

var arr =  [1,2,3,4,5];
console.log(arr.map((e)=> e + 2)) 

Sign up to request clarification or add additional context in comments.

1 Comment

1
const increaseByTwo = [1, 2, 3, 4, 5];

for (let i = 0; i < increaseByTwo.length; i++){ 

  increaseByTwo[i] = increaseByTwo[i] + 2;     //increaseByTwo[i] += 2;

}

console.log(increaseByTwo);

Comments

0

You can simply use .map() to get the resultant array:

const input = [1,2,3,4,5];

const output = input.map(v => v += 2);

console.log(output);

Comments

0

You can always use the .map() operator to modify element values. For example,

let increaseByTwo = [1,2,3,4,5];
increaseByTwo = increaseByTwo.map(num=>num+2);
console.log(increaseByTwo);

Or, if you really want to use a for loop, you can use this:

let increaseByTwo = [1,2,3,4,5];
for(let i = 0;i<increaseByTwo.length;++i){
  increaseByTwo[i]+=2;
}
console.log(increaseByTwo);

This should both work.

Comments

0

MyArray.map((elt)=>(elt+2));

This will basically pass each element into the function

(elt) => elt + 2

and will apply the result to the element. You can also do

for(var i = 0; i < MyArray.length; i++) {
    MyArray[i] += 2;
}

Now, for multiple operations and numbers. If you have something like [1, 2, 3, 4, 5] and you want to do the following [1 + 4, 2 * 6, 3 - 4, 4 / 8, 5 + 6]

var operators = '+*-/+'.split('');
var secondnums = [4,6,4,8,6];
var MyArray = [1,2,3,4,5]; 
for(var i = 0; i < MyArray.length; i++) {
    MyArray[i] = eval(MyArray[i]+operators[i]+secondnums[i]);
}

console.log(MyArray)
// [5, 12, -1, 0.5, 11] AKA [1 + 4, 2 * 6, 3 - 4, 4 / 8, 5 + 6]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.