Trying to solve symmetric difference using Javascript

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

    Another simple, yet readable solution:

     
    /*
    This filters arr1 and arr2 from elements which are in both arrays
    and returns concatenated results from filtering.
    */
    function symDiffArray(arr1, arr2) {
      return arr1.filter(elem => !arr2.includes(elem))
                 .concat(arr2.filter(elem => !arr1.includes(elem)));
    }
    
    /*
    Add and use this if you want to filter more than two arrays at a time.
    */
    function symDiffArrays(...arrays) {
      return arrays.reduce(symDiffArray, []);
    }
    
    console.log(symDiffArray([1, 3], ['Saluton', 3])); // [1, 'Saluton']
    console.log(symDiffArrays([1, 3], [2, 3], [2, 8, 5])); // [1, 8, 5]

    Used functions: Array.prototype.filter() | Array.prototype.reduce() | Array.prototype.includes()

提交回复
热议问题