Trying to solve symmetric difference using Javascript

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

    As with all problems, it's best to start off writing an algorithm:

    Concatenate versions of the arrays, where each array is filtered to contain those elements which no array other than the current one contains

    Then just write that down in JS:

    function sym() {
      var arrays = [].slice.apply(arguments);
    
      return [].concat.apply([],               // concatenate
        arrays.map(                            // versions of the arrays
          function(array, i) {                 // where each array
            return array.filter(               // is filtered to contain
              function(elt) {                  // those elements which
                return !arrays.some(           // no array
                  function(a, j) {             // 
                    return i !== j             // other than the current one
                      && a.indexOf(elt) >= 0   // contains
                    ;
                  }
                );
              }
            );
          }
        )
      );
    }
    

    Non-commented version, written more succinctly using ES6:

    function sym(...arrays) {
      return [].concat(arrays . 
        map((array, i) => array . 
          filter(elt => !arrays . 
            some((a, j) => i !== j && a.indexOf(elt) >= 0))));
    }
    

提交回复
热议问题