Trying to solve symmetric difference using Javascript

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

    My short solution. At the end, I removed duplicates by filter().

    function sym() {
      var args = Array.prototype.slice.call(arguments);
      var almost = args.reduce(function(a,b){
        return b.filter(function(i) {return a.indexOf(i) < 0;})
        .concat(a.filter(function(i){return b.indexOf(i)<0;}));
      });
      return almost.filter(function(el, pos){return almost.indexOf(el) == pos;});
    }
    
    sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]);
    
    //Result: [4,5,1]
    

提交回复
热议问题