es7: filter結合includes
// 並集
let union = a.concat(b.filter(v => !a.includes(v))) // [1,2,3,4,5]
// 交集
let intersection = a.filter(v => b.includes(v)) // [2]
// 差集
let difference = a.concat(b).filter(v => !a.includes(v) || !b.includes(v)) // [1,3,4,5]
es6: set資料結合array.form
let aset = new set(a)
let bset = new set(b)
// 並集
let union = array.from(new set(a.concat(b))) // [1,2,3,4,5]
// 交集
let intersection = array.from(new set(a.filter(v => bset.has(v)))) // [2]
// 差集
let difference = array.from(new set(a.concat(b).filter(v => !aset.has(v) || !bset.has(v)))) // [1,3,4,5]
es5可以利用filter和indexof進行數學集操作,但是,由於indexof方法中nan永遠返回-1,所以需要進行相容處理。
// 不考慮nan(陣列中不含nan)
// 並集
var union = a.concat(b.filter(function(v) )) // [1,2,3,4,5]
// 交集
var intersection = a.filter(function(v)) // [2]
// 差集
var difference = a.filter(function(v)).concat(b.filter(function(v))) // [1,3,4,5]
//考慮nan
var ahasnan = a.some(function(v))
var bhasnan = b.some(function(v))
// 並集
var union = a.concat(b.filter(function(v) )).concat(!ahasnan & bhasnan ? [nan] : ) // [1,2,3,4,5]
// 交集
var intersection = a.filter(function(v)).concat(ahasnan & bhasnan ? [nan] : ) // [2]
// 差集
var difference = a.filter(function(v)).concat(b.filter(function(v))).concat(ahasnan ^ bhasnan ? [nan] : ) // [1,3,4,5]
js陣列交集 並集 差集
1.利用filter indexof var arr1 1,2,3,4,5,6,7,8,9,nan arr2 1,3,5,nan var intersection arr1.filter function val console.log intersection 1,3,5 但這種方法針對是valu...
JS求陣列的交集 並集 差集
現有兩個陣列 let a 101,201,601 let b 201,301,801 複製 1.求交集 交集元素由既屬於集合a又屬於集合b的元素組成 方法1let intersection a.filter v b.includes v 201 複製 方法2 let intersection arr...
交集並集差集
1 內連線 select from student a inner join sc b on a.sno b.sno 左連線 select from student a left join sc b on a.sno b.sno 差集 select sno from student except s...