let array = [1,2,3,4,5,6]
for (element of array){
array[array.indexOf(element)]= element*2
}
console.log(array)
This is the code I wrote for doubling each element of an array but the output I’m getting is
(6) [8, 2, 12, 4, 10, 6]
What is the mistake I’m making?
Could someone please tell the logical error that I am making here .
3
Answers
The first time around the loop you read the first item and get
1
, then you find the first index which has the value1
and you change it to2
which leaves your array looking like:[2,2,3,4,5,6]
The second time around the loop you read the second item and get
2
, then you find the first index which has the value2
and you change it to4
which leaves your array looking like:[4,2,3,4,5,6]
… and so on.
Use a classic for loop and work based on the index.
Also consider using
map
and overwritingarray
with a new array with the doubled values.If you really wanted to use your syntax, you could have cloned the array to fix.
However, this answer is just for the example. It’s better to use solutions posted by Quentin.
Just to add to the collection of possible alternatives: if you really want to change the original array values then the following would work too: