How can I prevent mutation of the referenced Array

function canPartition(arr) {
	 let i=0;
	while(i< arr.length){
    let temp = arr;
		let val = temp[i];
		temp.splice(i,1)
    //console.log(temp)
    //console.log(val +":"+ temp.reduce((a,b)=> a*b))
		if(val == temp.reduce((a,b)=> a*b)){
			return true;
		}
		i++;
	}
	return false;
}

console.log(canPartition([-1, -20, 5, -1, -2, 2]))

What exactly happening here is the value of arr got changed when I am performing splice on temp i.e referenced to arr. How can I prevent this, I wants arr to be the same and when i value increased, it again get assign to temp.

Any help is appreciable thanks in advance :slight_smile:

you can use the spread operator like that:

const originalArr = [0, 1, 2, 3, 4, 5];
const copyArr  = [...originalArr]; // now if you mutate copyArr the originalArr stays intact

Good luck! :smile:

Note: this approach works only on level 1 deep, which means if you have for example an array like [0, 1, 2, [0, 1, 2]], mutating the inner array will still mutate the original after the copy, example:

const originalArr = [0, 1, 2, [0, 1, 2]];
const copyArr  = [...originalArr];
copyArr.shift() /* copyArr becomes  [1, 2, [0, 1, 2]],
but originalArr stays [0, 1, 2, [0, 1, 2]] */
//but
copyArr[2].shift()/*  copyArr becomes [1, 2, [1, 2]], 
and the original gets mutated also 
and becomes: [0, 1, 2, [1, 2]] */
1 Like

This is really informative. Thank you so much for your response. :slightly_smiling_face:

1 Like