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));