This array reassignment does not make sense to me

Kevin

So Im trying to solve this algorithm where I have to sum 4 numbers from given array(first parameter) in order to get second passed parameter, and Im doing it in a pretty stupid way (question not about solving the algorithm). Question is: why I can't delete values from array and recreate/reassign itself again, hope that make sence. Is it just how Javascript works or I did something wrong? Thanks in advance!

function foo(arr1, sum){
      let arr = arr1;
      for(let i=0; i<9999;i++){
        let val1=arr[Math.floor(Math.random()*arr.length)];
        arr.splice(arr.indexOf(val1),1);
         console.log(arr1);
        let val2=arr[Math.floor(Math.random()*arr.length)];
        arr.splice(arr.indexOf(val2),1);
        let val3=arr[Math.floor(Math.random()*arr.length)];
        arr.splice(arr.indexOf(val3),1);
        let val4=arr[Math.floor(Math.random()*arr.length)];
        arr.splice(arr.indexOf(val4),1);
        if(val1+val2+val3+val4 == sum){
          console.log(val1,val2,val3,val4);
         return [val1,val2,val3,val4]; 
        }

       arr=arr1;
      }
    }
    console.log(foo([2, 7, 4, 0, 9, 5, 1, 3], 20));
Jonas Wilms

Actually arr1 is not the array itself but a Reference to it. If you do arr = arr1 you copy that Reference, and that Reference points to the same array as arr1. Therefore if you change the array arr is referencing, you also change the array arr1 is referencing. To copy an array:

 arr = arr1.slice();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related