skip to Main Content
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


  1. The first time around the loop you read the first item and get 1, then you find the first index which has the value 1 and you change it to 2 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 value 2 and you change it to 4 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.

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

    Also consider using map and overwriting array with a new array with the doubled values.

    let array = [1,2,3,4,5,6]
    array = array.map(value => value * 2);
    console.log(array);
    
    Login or Signup to reply.
  2. 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.

    let array = [1,2,3,4,5,6]
    let clonedArr = [...array];
    for (element of clonedArr){
     array[clonedArr.indexOf(element)]= element*2
    }
    console.log(array)
    Login or Signup to reply.
  3. 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:

    let array = [1,2,3,4,5,6]
    array.forEach((_,i,a)=>a[i]*=2)
    console.log(array)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search