最效率获得俩个数组的相同值

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)

    })

})

你们代码需要怎么改才能实现原来的目的,改动最少最简单的,我认为是最合理的就采纳了


互换的青春
浏览 696回答 2
2回答

慕莱坞森

let arr1=['a','b','c','d','e']let arr2=['c','d','g','h','a']let res = []var a = arr2.filter(v => {&nbsp; &nbsp; if (arr1.indexOf(v) >= 0) {&nbsp; &nbsp; &nbsp; &nbsp; res.push(v)&nbsp; &nbsp; }&nbsp; &nbsp; return arr1.indexOf(v) < 0})res // ["c", "d", "a"]a // ["g", "h"]

慕森王

array 转 dictlet arr1=['a','b','c','d','e']let arr2=['c','d','g','h','a']let obj = arr1.reduce((iter, val) => {&nbsp; &nbsp; iter[val] = true&nbsp; &nbsp; return iter}, {})let result = arr2.filter(v => !obj[v])console.log(result)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript