JavaScript中对比两个数组,一个数组与另一个数组不相等的部分

171 阅读1分钟

首先需要两个数组,这里直接致敬下Element-ui的table数据

tableData: [
   { date: '2016-05-02', name: '王小鼠', address: '上海市普陀区金沙江路 1518 弄' }, 
   { date: '2016-05-04', name: '王小牛', address: '上海市普陀区金沙江路 1517 弄' }, 
   { date: '2016-05-01', name: '王小虎', address: '上海市普陀区金沙江路 1519 弄' }, 
   { date: '2016-05-03', name: '王小羊', address: '上海市普陀区金沙江路 1516 弄' }
 ]
 
 dataTable: [
   { date: '2016-05-02', name: '王小龙', address: '上海市普陀区金沙江路 1518 弄' }, 
   { date: '2016-05-04', name: '王小蛇', address: '上海市普陀区金沙江路 1517 弄' }, 
   { date: '2016-05-01', name: '王小虎', address: '上海市普陀区金沙江路 1519 弄' }, 
   { date: '2016-05-03', name: '王小羊', address: '上海市普陀区金沙江路 1516 弄' }
 ]

之后使用filter和every 对比出第一个数组里name与第二个不相同的部分

let arrTools = tableData.filter( filItem => dataTable.every(eveItem => !Object.is(filItem.name,eveItem.name)))

arrTools:[
    {
        "date": "2016-05-02",
        "name": "王小鼠",
        "address": "上海市普陀区金沙江路 1518 弄"
    },
    {
        "date": "2016-05-04",
        "name": "王小牛",
        "address": "上海市普陀区金沙江路 1517 弄"
    }
]

//取出了数组tableData中与dataTable中不相等的部分

这里使用了ES6的filter、every、Object.is()来实现求数组的补集

为了方便大家观看,形参使用了应该能更清晰的写法