如下兩個(gè)[數(shù)組]對(duì)象a和b
let a=[{id:1,value:'this'},{id:2,value:'is'}]
let b=[{id:1,value:'hello'},{id:3,value:'world'}]
filter() 方法創(chuàng)建一個(gè)新的數(shù)組,新數(shù)組中的元素是通過(guò)檢查指定數(shù)組中符合條件的所有元素。
some() 方法用于檢測(cè)數(shù)組中的元素是否滿足指定條件(函數(shù)提供)。
includes() 方法用來(lái)判斷一個(gè)數(shù)組是否包含一個(gè)指定的值,如果是返回 true,否則false.也可以匹配字符串。
indexOf() 方法可返回某個(gè)指定的字符串值在字符串中首次出現(xiàn)的位置。
ES6的Set 和 Map
方法 描述
add 添加某個(gè)值,返回Set對(duì)象本身。
clear 刪除所有的鍵/值對(duì),沒(méi)有返回值。
delete 刪除某個(gè)鍵,返回true。如果刪除失敗,返回false。
forEach 對(duì)每個(gè)元素執(zhí)行指定操作。
has 返回一個(gè)布爾值,表示某個(gè)鍵是否在當(dāng)前 Set 對(duì)象之中。
方法1、使用filter() , some()
let newList = b.filter(item => !a.some(x => x.id === item.id ))
// newList: [{id:3,value:"world"}]
方法2、使用filter(),includes()
let s = a.map(x => x.id)
let newList = b.filter(item => !s.includes(item.id))
// newList: [{id:3,value:"world"}]
方法3、使用filter(), indexOf()
let s = a.map(x => x.id)
let newList = b.filter(item => s.indexOf(item.id) === -1)
// newList: [{id:3,value:"world"}]
方法4、使用filter(), Set(),map()
const s = new Set(a.map(x => x.id))
const newList1 = b.filter(x => !s.delete(x.id))
const newList2 = a.filter(x => s.has(x.id))
// newList1: [{id:3,value:"world"}]
// newList2: [{id:2,value:"is"}]