0

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));
Kevin
  • 497
  • 1
  • 5
  • 13
  • You can - just before you use it again - declare it as a new array. Eg: arr = new Array(); then arr = arr1. After that you can use this to assign your values - unless I am missing the question here..... – alpharomeo Oct 10 '18 at 19:45
  • @alpharomeo that won't change anything – Jonas Wilms Oct 10 '18 at 19:46

1 Answers1

0

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();
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151