let arr1=['a','b','c','d','e']let arr2=['c','d','g','h','a']找到arr1和arr2中相同的值,并在arr2中删除对应的值怎么写才更简单效率,我只能想到套个双层循环,就比如这样 arr1.forEach((val)=>{ arr2.forEach((v,i)=>{ val === v && arr2.splice(i,1) }) })然后现在问题变了arr2=[{'id':'c'},{'id':'d'},{'id':'g'},{'id':'h'},{'id':'a'}]我的只要改一个地方就能继续运行arr1.forEach((val)=>{ arr2.forEach((v,i)=>{ val === v.id && arr2.splice(i,1) })})你们代码需要怎么改才能实现原来的目的,改动最少最简单的,我认为是最合理的就采纳了
2 回答
慕莱坞森
TA贡献1810条经验 获得超4个赞
let arr1=['a','b','c','d','e']
let arr2=['c','d','g','h','a']
let res = []
var a = arr2.filter(v => {
if (arr1.indexOf(v) >= 0) {
res.push(v)
}
return arr1.indexOf(v) < 0
})
res // ["c", "d", "a"]
a // ["g", "h"]
慕森王
TA贡献1777条经验 获得超3个赞
array 转 dict
let arr1=['a','b','c','d','e']
let arr2=['c','d','g','h','a']
let obj = arr1.reduce((iter, val) => {
iter[val] = true
return iter
}, {})
let result = arr2.filter(v => !obj[v])
console.log(result)
添加回答
举报
0/150
提交
取消