Trying to solve symmetric difference using Javascript

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

    // Set difference, a.k.a. relative compliment
    const diff = (a, b) => a.filter(v => !b.includes(v))
    
    const symDiff = (first, ...rest) => 
      rest.reduce(
        (acc, x) => [
          ...diff(acc, x), 
          ...diff(x, acc),
        ], 
        first,
      )    
    
    /* - - - */
    console.log(symDiff([1, 3], ['Saluton', 3]))    // [1, 'Saluton']
    console.log(symDiff([1, 3], [2, 3], [2, 8, 5])) // [1, 8, 5]

提交回复
热议问题