前提:有两个数组,数组A和数组B,假设数组B是数组A的子集,遍历这两个数组,然后把数组B中缺少的数组A的元素添加到数组B中
如:
数组A:
let arrA = [
{
id: 1,
data: [
{times: 6, type: 1},
{times: 23, type: 2},
{times: 6, type: 3}
]
},
{
id: 2,
data: [
{times: 3, type: 1},
{times: 8, type: 3}
]
},
{
id: 3,
data: [
{times: 6, type: 1},
{times: 2, type: 3}
]
},
{
id: 4,
data: [
{times: 5, type: 2},
{times: 1, type: 3}
]
},
{
id: 5,
data: [
{times: 3, type: 2}
]
}
]
数组B:数组B的由来是遍历数组A,再遍历data,找到 type: 1
的元素取出来
let arrB = [
{
id: 1,
times: 6
},
{
id: 2,
times: 3
},
{
id: 3,
times: 6
},
]
接下来就是补全 数组B:arrB,如果不存在id,则 times: 0
遍历两个数组找出不同的元素
getFor(allArr, lessArr) {
let arr = []
if (lessArr.length !== allArr.length) {
for (let i = 0; i < allArr.length; i++) {
let isExist = false // 声明一个boolean值,不然循环不对
for (let j = 0; j < lessArr.length; j++) {
if (lessArr[j].id=== allArr[i].id) {
isExist = true
break
}
}
if (!isExist) {
arr.push({
id: allArr[i].id,
times: 0
})
}
}
return arr
} else {
return []
}
}
...
arrB= [...arrB, ...this.getFor(arrA, arrB)]
...
最终 arrB :
arrB = [
{
id: 1,
times: 6
},
{
id: 2,
times: 3
},
{
id: 3,
times: 6
},
{
id: 4,
times: 0
},
{
id: 5,
times: 0
},
]
找出2个数组不同的元素
数组对象也是一样
const oldVal = ['4620214765279510529', '4626834100420870145']
const newVal = ['4620214765279510529']
const res = oldVal.filter((e) => !newVal.some((e2) => e2 === e));
console.log(res) // ['4626834100420870145']