陣列去重 並集 交集 差集

2021-09-25 21:37:48 字數 1542 閱讀 8449

一、去重

1、借助額外變數空間-es5

var arr = [1,3,4,5,6,6,7,3,3,3]

var newarr =

var obj = {}

function removeduplicates(arr)

} return newarr;

}removeduplicates(arr);

//[1,3,4,5,6,7]

2、不借助額外變數空間(原地去重)-es5

var arr = [1,3,4,5,6,6,7,3,3,3]

var removeduplicates = function(nums)

}return nums;

};removeduplicates(arr);

//[1,3,4,5,6,7]

3、set去重-es6:上述兩種es5的去重方法只對數字陣列或字串陣列有效,對於含有物件的陣列則無法達到去重效果,es6新提出set方法則可以

const obj = 

const arr = [1,3,4,5,6,6,7,3,3,3,obj,obj]

const os = new set(arr);

const newarr = [...os];//[1, 3, 4, 5, 6, 7,]

二、利用set取交集-es6

const arr1 = [1,3,4,5,3]

const arr2 = [1,2,7,8,3]

const os = new set([...arr1,...arr2])

console.log([...os]);//[1,2,3,4,5,7,8]

三、set取並集-es6

const arr1 = [1,3,4,5,3]

const arr2 = [1,2,7,8,3]

const os1 = new set(arr1)

const os2 = new set(arr2)

const newarr = [...os1].filter(ele => os2.has(ele))

console.log(newarr);//[1,3]

四、set取差集-es6

const arr1 = [1,3,4,5,3]

const arr2 = [1,2,7,8,3]

const os1 = new set(arr1)

const os2 = new set(arr2)

const newarr1 = [...os1].filter(ele => !os2.has(ele))

const newarr2 = [...os2].filter(ele => !os1.has(ele))

const newarr = [...newarr1,...newarr2];

console.log(newarr);//[2,3,4,5,7,8]

JS陣列操作 去重,交集,並集,差集

原文 js陣列操作 去重,交集,並集,差集 方法一 function unique arr 方法二 function unique arr 方法三 function unique arr a 1,2,3 b 2,4,5 方法一 es7新增了乙個array.prototype.includes的陣列方...

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...

交集並集差集

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...