Find the Symmetric Difference Feedback

Hello, I’ve just solved the symmetric difference challenge (hope to contribute to the collection of all possible solutions) and would love to have some feedback on how I can make the code more readable, or if there is a more elegant way for the solution. Thank you!

function sym(...args) {
  let arr1 = []  // This will hold our accumulated result
  
  for (let i = 0; i < args.length-1; i++) {
    if (i == 0) {
      let unique1 = [...new Set(args[i])]
      let unique2 = [...new Set(args[i+1])]
      // Compare args[0] and args[1]
      for (let j = unique1.length-1; j >= 0; j--) {
        for (let k = unique2.length-1; k >= 0; k--) {
          if (unique1[j] == unique2[k]) {
            unique1.splice(j, 1)
            unique2.splice(k, 1)
          }
        }
      }
      let arr = new Set(unique1.concat(unique2))
      arr1 = [...arr]  // update outer variable
    } else {
      let unique2 = [...new Set(args[i+1])]
      for (let j = arr1.length-1; j >= 0; j--) {
        for (let k = unique2.length-1; k >= 0; k--) {
          if (arr1[j] == unique2[k]) {
            arr1.splice(j, 1)
            unique2.splice(k, 1)
          }
        }
      }
      let arr = new Set(arr1.concat(unique2))
      arr1 = [...arr]
    } 
  }
  console.log(arr1)
  return arr1;
}

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]);

hello and welcome to fcc forum :slight_smile:

well done :clap: , btw, is this some thing from fcc curriculum? if so then adding that link would be very useful and recommended…

  • what does this snippet does? as in reason behind it you are comparing them
  • this snippet seems to be a good candidate for DRY concept in that function

happy coding :slight_smile:

Few comments:

  • Naming things, if ie. arr1 needs comment to explain what it contains, it could use better name.
  • Using splice and changing length of both arrays when they are being iterated over. This could be very tricky to debug if something would not work as intended.
  • Is it really needed to have separate code handling i == 0 and different values of i?
  • Using Set to remove duplicates. This wasn’t really forbidden, but it’s simplifying part of the task. Task, which is to reproduce other feature of sets, so… :face_with_tongue:
  • Could be a personal preference, but usually I find (let j = 0; j < arr1.length; j++) much easier to read, instead of(let j = unique1.length-1; j >= 0; j--). Note: it will not work when using splice and changing length of array that’s being iterated over.