day53-两数组-集合运算

背景

选择语言对的时候,源语言和目标语言选项要互斥。由此联想到交集、差集、补集、并集的JS如何实现。本文小结ES5和ES6的一些实现方法。

Photo by Ant Rozetsky on Unsplash
[Photo by Ant Rozetsky on Unsplash]

ES5实现

  • 数据
    let arrA = [‘a’, 3, 5, ‘d’, ‘o’]
    let arrB = [‘b’, 5, ‘o’, ‘x’, ‘g’, ‘b’]

    filter+indexOf+concat

  • 交集

    let intersection = arrA.filter(v => {
    return arrB.indexOf(v) > -1
    })
    console.log(intersection)
    // [ 5, 'o' ]
  • 差集

    arrA与arrB的差集

    let r = arrA.filter(v => {
    return arrB.indexOf(v) > -1
    })
    console.log(r)
    // [ 'a', 3, 'd' ]
  • 补集

    let complementarySet = arrA
    .filter(v => !(arrB.indexOf(v) > -1))
    .concat(arrB.filter(v => !(arrA.indexOf(v) > -1)))
    console.log(complementarySet)
    // [ 'a', 3, 'd', 'b', 'x', 'g', 'b' ]
  • 并集

    let unionSet = arrA.concat(arrB.filter(v => !(arrA.indexOf(v) > -1)))
    console.log(unionSet)
    // [ 'a', 3, 5, 'd', 'o', 'b', 'x', 'g', 'b' ]

ES6实现

  • 数据
    let arrA = [‘a’, 3, 5, ‘d’, ‘o’]
    let arrB = [‘b’, 5, ‘o’, ‘x’, ‘g’, ‘b’]

    filter+Set+has

  • 交集

    let intersection = arrA.filter(x => new Set(arrB).has(x))
    console.log(intersection)
    // [ 5, 'o' ]
  • 差集

    arrA与arrB的差集

    let diffSet = arrA.filter(x => !new Set(arrB).has(x))
    console.log(diffSet)
    // [ 'a', 3, 'd' ]
  • 补集

    let complementarySet = [...arrA.filter(x => !new Set(arrB).has(x)), ...arrB.filter(x => !new Set(arrA).has(x))]
    console.log(complementarySet)
    // [ 'a', 3, 'd', 'b', 'x', 'g', 'b' ]
  • 并集

    let unionSet = Array.from(new Set([...arrA, ...arrB]))
    console.log(unionSet)
    // [ 'a', 3, 5, 'd', 'o', 'b', 'x', 'g' ]
文章作者: lmislm
文章链接: http://lmislm.com/2019/03/05/2019-03-05/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog