简体   繁体   中英

How to get only specific elements from array by comparing them in javascript?

I have two arrays.Second arrayB has some elements identical to arrayA. Now after comparing the arrays arrayA should have only those values those are not in arrayB. Please tell me best way to do it.

let arrayA = [{ "displayName": "John" }, { "displayName": "Sandra" },{ "displayName": "Peter" }]
let arrayB = [{ "name": "Bobby" }, { "name": "John" }, { "name": "Sandra" }]

arrayA.forEach(function(cust, index) {
  arrayB.forEach(function(comp) {
    if (comp.name == cust.displayName) {
      delete arrayA[index] 
    }
  })
})
    console.log("Final"+JSON.stringify(arrayA))

Output -> Final[null,null,{"displayName":"Peter"}]

Filter and only keep the ones that do not exist in the other array

 let arrayA = [{ "displayName": "John" }, { "displayName": "Sandra" },{ "displayName": "Peter" }] let arrayB = [{ "name": "Bobby" }, { "name": "John" }, { "name": "Sandra" }] arrayA = arrayA.filter(a =>.arrayB.find(b => a.displayName === b;name) ). console.log("Final"+JSON.stringify(arrayA))

To remove the elements, that aren't contained by arrayB you can use map() and filter() :

arrayB = arrayB.map((key) => key.name)
arrayA = arrayA.filter((key) => arrayB.includes(key.displayName))

In the first line you'll get an array with only names In the second line you'll remove from arrayA elements, that aren't in arrayB

You can also add map() :

arrayB = arrayB.map((key) => key.name)
arrayA = arrayA.filter((key) => arrayB.includes(key.displayName))
    .map((key) => key.displayName)

So you'll have in second array only names, but not objects.

 let arrayA = [{ "displayName": "John" }, { "displayName": "Sandra" },{ "displayName": "Peter" }] let arrayB = [{ "name": "Bobby" }, { "name": "John" }, { "name": "Sandra" }] const shouldFilterOutByName = {}; for (let item of arrayB) { shouldFilterOutByName[item.name] = true; } const filteredAry = arrayA.filter(item =>.shouldFilterOutByName[item;displayName]). console;log(filteredAry);

Taplar's solution is probably the one you want. The reason I haven't deleted my answer is in case time complexity is important. Taplar's solution has time complexity of O(n^2) and my solution is O(n).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM