Trying to solve symmetric difference using Javascript

后端 未结 16 1425
伪装坚强ぢ
伪装坚强ぢ 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:41

    I came across this question in my research of the same coding challenge on FCC. I was able to solve it using for and while loops, but had some trouble solving using the recommended Array.reduce(). After learning a ton about .reduce and other array methods, I thought I'd share my solutions as well.

    This is the first way I solved it, without using .reduce.

    function sym() {
      var arrays = [].slice.call(arguments);
    
      function diff(arr1, arr2) {
        var arr = [];
    
        arr1.forEach(function(v) {
          if ( !~arr2.indexOf(v) && !~arr.indexOf(v) ) {
            arr.push( v );
          }
        });
    
        arr2.forEach(function(v) {
          if ( !~arr1.indexOf(v) && !~arr.indexOf(v) ) {
            arr.push( v );
          }
        });
        return arr;
      }
    
      var result = diff(arrays.shift(), arrays.shift());
    
      while (arrays.length > 0) {
        result = diff(result, arrays.shift());
      }
    
      return result;
    }
    

    After learning and trying various method combinations, I came up with this that I think is pretty succinct and readable.

    function sym() {
      var arrays = [].slice.call(arguments);
    
      function diff(arr1, arr2) {
        return arr1.filter(function (v) {
          return !~arr2.indexOf(v);
        });
      }
    
      return arrays.reduce(function (accArr, curArr) { 
        return [].concat( diff(accArr, curArr), diff(curArr, accArr) )
        .filter(function (v, i, self) { return self.indexOf(v) === i; });
      });
    
    }
    

    That last .filter line I thought was pretty cool to dedup an array. I found it here, but modified it to use the 3rd callback parameter instead of the named array due to the method chaining.

    This challenge was a lot of fun!

提交回复
热议问题