【求解答?】如何比较两个数组,得出相同的元素和不同的元素?
发布于 7 年前 作者 tanchao 2050 次浏览 来自 问答

我之前测试的,不管用

let list1 = ['a', 'b','c' ];

let list2 = ['a', 'b'];

let same = [];

let tet =[]

for (let i = 0; i < list1.length; i++) {

for (let p = 0; p < list1.length; p++) {

if (list1[i]!=list2[p]) {

same.push(list1[i])

}else{

tet.push(list1[i])

}

}

请教一下,如何运算得出相同元素为a,b,不同的元素c

想获得比较数组比较好用的方法

3 回复

数组

取并集

let a=new Set([1,2,3,4,5]);

let b=new Set([1,2,3,4,5,6,7,8,9]);

let arr = Array.from(new Set([…a, …b]));

console.log(‘arr’,arr);

取交集

let a=new Set([1,2,3,4,5]);

let b=new Set([1,2,3,4,5,6,7,8,9]);

let arr = Array.from(new Set([…b].filter(x => a.has(x))));

取差集

let a=new Set([1,2,3,4,5]);

let b=new Set([1,2,3,4,5,6,7,8,9]);

let arr = Array.from(new Set([…b].filter(x => !a.has(x))));

console.log(‘arr’,arr);

数组对象

取交集

let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234}];

let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];

let arr = […b].filter(x => […a].some(y => y.id === x.id));

console.log(‘arr’,arr)

取差集

let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234}];

let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];

let arr = […b].filter(x => […a].every(y => y.id !== x.id));

console.log(‘arr’,arr);

算法题都来问了?

--↓↓👍如果觉得有帮助的话请点个【赞】吧(我的小尾巴又肥来啦!)

回到顶部