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]
-
Results don't turn out to be like that.Taha Paksu– Taha Paksu2018年12月27日 06:01:19 +00:00Commented Dec 27, 2018 at 6:01
-
how do i modify my results to make it look nice as a list?JuniorSQL– JuniorSQL2018年12月27日 06:03:38 +00:00Commented Dec 27, 2018 at 6:03
-
in the console or in the browser? stackoverflow.com/questions/46141450/…Taha Paksu– Taha Paksu2018年12月27日 06:05:14 +00:00Commented Dec 27, 2018 at 6:05
-
Possible duplicate of With JavaScript how would I increment numbers in an array using a for loop?adiga– adiga2018年12月27日 06:19:53 +00:00Commented Dec 27, 2018 at 6:19
5 Answers 5
var arr = [1,2,3,4,5];
console.log(arr.map((e)=> e + 2))
1 Comment
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
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
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
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]