Algorithms - Find the Symmetric Difference - temp variable gets modified despite being untouched

I am storing the arguments in a temp variable and have not used it anywhere other than as the upper limit while initiating the loop.
I modify the args array by reassigning the first element and removing the second at the end of each loop. the temp array remains untouched.
however, the temp array is also being modified. Please let me know why this might be happening

here’s the console log
initial temp: [ [ 3, 3, 3, 2, 5 ], [ 2, 1, 5, 7 ], [ 3, 4, 6, 6 ], [ 1, 2, 3 ] ]

loop: 0
temp: [ [ 3, 3, 3, 2, 5 ], [ 2, 1, 5, 7 ], [ 3, 4, 6, 6 ], [ 1, 2, 3 ] ]
args: [ [ 3, 3, 3, 2, 5 ], [ 2, 1, 5, 7 ], [ 3, 4, 6, 6 ], [ 1, 2, 3 ] ]

loop: 1
temp: [ [ 3, 3, 3, 1, 7 ], [ 3, 4, 6, 6 ], [ 1, 2, 3 ] ]
args: [ [ 3, 3, 3, 1, 7 ], [ 3, 4, 6, 6 ], [ 1, 2, 3 ] ]

Your code so far

function sym(...args) {
  let temp = args
  console.log(temp)
  for(let i=0; i<temp.length; i++){
    console.log("\nloop: ",i)
    console.log("temp: ", temp, "\nargs:" , args)

    let a = complement(args[0], args[1])
    let b = complement(args[1], args[0])

    let finalArray = [...a,...b]
    args[0] = finalArray
    args.splice(1,1)

  }
  let symArr = args[0].filter((item,index)=> args[0].indexOf(item)===index)
  console.log(symArr)
  return symArr;
}
function complement(arr1, arr2){
  let result=[];
  for (let j=0; j<arr1.length; j++){
    let equal= false
    for(let k=0; k<arr2.length; k++){
      if(arr1[j] == arr2[k]){
          equal=true
      }
    }
    if(!equal){
      result.push(arr1[j])
    }
  }
  return result
}
sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Algorithms - Find the Symmetric Difference

Link to the challenge:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.