求数组的并集,交集,差集,并集升序,并集降序
对...扩展运算符不熟悉的可以参考我的文章 es6 ...扩展运算符
var arr1 = [3, 4, 22, 12];
var arr2 = [3, 4, 6, 8];
var bj = [...new Set([...arr1, ...arr2])];
var jj = arr1.filter(v => new Set(arr2).has(v));
var cj = [...arr1.filter(v => !new Set(arr2).has(v)), ...arr2.filter(v => !new Set(
arr1)
.has(v))];
var bjSort = [...new Set([...arr1, ...arr2])].sort((a, b) => a - b);
var bjDrop = [...new Set([...arr1, ...arr2])].sort((a, b) => b - a);
console.log("%c%s", "color:red", "并集", bj); //[3, 4, 22, 12, 6, 8]
console.log("%c%s", "color:red", "交集", jj); //[3, 4]
console.log("%c%s", "color:red", "差集", cj); //[22, 12, 6, 8]
console.log("%c%s", "color:red", "并集升序", bjSort); //[3, 4, 6, 8, 12, 22]
console.log("%c%s", "color:red", "并集降序", bjDrop); //[22, 12, 8, 6, 4, 3]
原文作者:匆匆那年_海,博客主页:http://08643.cn/u/910c0667c515
95后前端汉子,爱编程、优秀、聪明、理性、沉稳、智慧的程序猿一枚。