Trying to solve symmetric difference using Javascript

后端 未结 16 1443
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 10:12

I am trying to figure out a solution for symmetric difference using javascript that accomplishes the following objectives:

  • accepts an unspecified number of ar
16条回答
  •  忘掉有多难
    2020-11-29 10:37

    function sym(arr1, arr2, ...rest) {
    
      //creating a array which has unique numbers from both the arrays
      const union = [...new Set([...arr1,...arr2])];
    
      // finding the Symmetric Difference between those two arrays
      const diff = union.filter((num)=> !(arr1.includes(num) && arr2.includes(num)))
    
      //if there are more than 2 arrays
      if(rest.length){
        // recurrsively call till rest become 0 
        // i.e.  diff of 1,2 will be the first parameter so every recurrsive call will reduce     //  the arrays till diff between all of them are calculated.
    
        return sym(diff, rest[0], ...rest.slice(1))
      }
      return diff
    }
    

提交回复
热议问题