<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
<div id="app">
<table>
<tbody>
<tr>
<td>oldList:{{oldList}}</td>
</tr>
<tr>
<td>newList:{{newList}}</td>
</tr>
<tr>
<td>表示newList与并集的差集(删掉的数据){{oldDifference}}</td>
</tr>
<tr>
<td>表示oldList与newList的交集(未修改的数据){{intersection}}</td>
</tr>
<tr>
<td>表示oldList与并集的差集(新增的数据){{newDifference}}</td>
</tr>
</tbody>
</table>
</div>
普通写法:
new Vue({
el: '#app',
data: {
oldList: [422, 423, 424, 425, 426, 427],
newList: [426, 427, 428, 429, 430, 431],
bucket: [], //定义一个空桶
intersection: [],//old与new的交集
oldDifference: [],//old与并集的差集
newDifference: []//new与并集的差集
},
created() {
this.oldList.forEach((item) => { //设置桶的索引为new数据的数据,参数设置为0
this.bucket[item] = 0 //422: 0,423: 0,424: 0,425: 0,426: 0,427: 0
})
console.log(this.bucket);
this.newList.forEach((item) => {
if (this.bucket[item] !== undefined) {
this.bucket[item] = 1
} else {
this.bucket[item] = 2
}
// 422: 0,423: 0,424: 0,425: 0,426: 1,427: 1,428: 2,429: 2,430: 2,431: 2
})
var object = this.bucket
for (const key in object) {
if (object[key] == 0) {
this.oldDifference.push(key);
} else if (object[key] == 2) {
this.newDifference.push(key);
} else {
this.intersection.push(key);
}
}
}
})
ES6 Set写法:
new Vue({
el: '#app',
data: {
oldList: [422, 423, 424, 425, 426, 427],
newList: [426, 427, 428, 429, 430, 431],
intersection: [],//old与new的交集
oldDifference: [],//old与并集的差集
newDifference: []//new与并集的差集
},
created() {
let union = new Set([...this.oldList, ...this.newList]);// 并集
let oldSet = new Set(this.oldList)
let newSet = new Set(this.newList)
// newList与并集的差集
this.oldDifference = [...new Set([...union].filter(x => !newSet.has(x)))];
// newList与oldSet的交集
this.intersection = [...new Set([...oldSet].filter(x => newSet.has(x)))];
// oldList与并集的差集
this.newDifference = [...new Set([...union].filter(x => !oldSet.has(x)))];
}
})