两个数组中包含对象,查找出数组1相对数组2差值

<script>
	let arr1 = [
		{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"}
	];
	let arr2 = [
		{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"}
	];

	let arrtemp = arr2.map((item) => {
		return item.fpcid;
	});
	let json = arr1.find((item) => {
		return !arrtemp.includes(item.fpcid);
	});
	console.log(json);
</script>

这样可以快速找出arr1比arr2多的第一个对象,如果要找出所有对象,可以将find改为filter

另有一种嵌套方法,性能较差

<script>
        let arr1 = [
		{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"}
	];
	let arr2 = [
		{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"}
	];
	let json = arr1.find((item) => {
		let flag = true;
		arr2.forEach((value) => {
			if (item.fpcNameCode == value.fpcNameCode) {
				flag = false;
			}
		});
		return flag;
	});
	console.log(json);
</script>

性能测试

<script>
	let arr1 = [
		{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"}
	];
	let arr2 = [
		{fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
		{fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"}
	];
	let i = 0;
	while (i < 10000) {
		arr1.push({fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"});
		arr2.push({fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"});
		i++;
	}
	let t1 = new Date().getTime();
	let arrtemp = arr2.map((item) => {
		return item.fpcid;
	});
	let json = arr1.filter((item) => {
		return !arrtemp.includes(item.fpcid);
	});
	let t2 = new Date().getTime();
	console.log(t2 - t1);   //4
	console.log(json);
	let t3 = new Date().getTime();
	let json1 = arr1.filter((item) => {
		let flag = true;
		arr2.forEach((value) => {
			if (item.fpcNameCode == value.fpcNameCode) {
				flag = false;
			}
		});
		return flag;
	});
	let t4 = new Date().getTime();
	console.log(t4 - t3);  //900
	console.log(json1);
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值