【js】实现两个数组求差集

js实现两个数组求差集

  1. 使用数组的 filter() + includes()方法
let array1 = [1, 2, 3, 4, 5];  
let array2 = [3, 4, 5, 6, 7];

let difference = array1.filter(x => !array2.includes(x)); 
 
console.log(difference); // 输出:[1, 2]

也可以将 includes()方法替换成 indexOf()

let difference = array1.filter(x => array2.indexOf(x) === -1); // [1,2]
  1. 使用Set对象:
let array1 = [1, 2, 3, 4, 5];  
let array2 = [3, 4, 5, 6, 7];  
  
let set1 = new Set(array1);  
let set2 = new Set(array2);  
  
let difference = [...set1].filter(x => set2.size === 0 || !set2.has(x));  
  
console.log(difference); // 输出:[1, 2]

你可能感兴趣的:(学习记录—JS,javascript,前端,开发语言)