Trying to solve symmetric difference using Javascript

后端 未结 16 1433
伪装坚强ぢ
伪装坚强ぢ 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 11:02

    function sym(args) {
      var initialArray = Array.prototype.slice.call(arguments);
      var combinedTotalArray = initialArray.reduce(symDiff);
    
      
      // Iterate each element in array,  find values not present in other array and push values in combinedDualArray if value is not there already
      // Repeat for the other array (change roles)
      function symDiff(arrayOne, arrayTwo){
        var combinedDualArray = [];
        arrayOne.forEach(function(el, i){
          if(!arrayTwo.includes(el) && !combinedDualArray.includes(el)){
            combinedDualArray.push(el);
          }
        });
          
        arrayTwo.forEach(function(el, i){
          if(!arrayOne.includes(el) && !combinedDualArray.includes(el)){
            combinedDualArray.push(el);
          }
        });
        combinedDualArray.sort();
        return combinedDualArray;
      }
      
      return combinedTotalArray;
    }
    
    console.log(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]));

提交回复
热议问题