0

in the code below i am able to compare 2 arrays and filter out elements that are not including in the first array.

const a = [1,2,3,4,5];
const b = [1,3]

const elements_in_a_not_in_b = a.filter((element) => !b.includes(element))

console.log(
  elements_in_a_not_in_b
)

But now i want to solve this problem for Arrays that contains only objects. How this can be done?

const a = [Object,Object,Object,Object,Object];
const b = [Object,Object]
Suppe
  • 189
  • 2
  • 5
  • 12
  • 1
    http://jsbin.com/modufigude/1/edit?js,console — The same way. What's the problem? – Quentin Aug 15 '17 at 14:50
  • 2
    Possible duplicate of [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – Phylogenesis Aug 15 '17 at 14:53
  • thanks Quentin for your help – Suppe Aug 15 '17 at 14:56
  • 1
    Quentin's solution only works if the *exact* same object is referenced by both arrays. It doesn't work if you have identical items declared separately. See here: http://jsbin.com/xayuwawuwe/edit?js,console – Cineris Aug 15 '17 at 15:26
  • Possible duplicate of [Comparing Arrays of Objects in JavaScript](https://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript) – Ulysse BN Aug 15 '17 at 16:01

1 Answers1

1

You want to iterate through each element in a and check if there are any matches on b, if not, add it to the output.

function getElementsInANotInB(a,b){
    var results = []
    for(var i=0;i<a.length;i++){
        var in_b = false
        // check if any element in b matches a[i]
        for(var u=0;u<b.length;u++){
            if(compareObjects(a[i],b[u])){ 
                in_b = true
                break
            }
        }
        if(!in_b) // no element in b matched a[i], add to results
            results.push(a[i])
    }
    return results
}

function compareObjects(obj1,obj2,reversed){
    // search for differences recursively
    for(var key in obj1){
        if(typeof obj2[key]=="undefined") return false
        if(typeof obj1[key] == "object"){
            if(!compareObjects(obj1[key],obj2[key])) return false
        }
        else if(obj1[key]!=obj2[key]) return false
    }
    return reversed ? true : compareObjects(obj2,obj1,true)
}

Calling getElementsInANotInB(a,b) should give you the desired array containing all elements in a, which are not in b.

Manuel Otto
  • 6,410
  • 1
  • 18
  • 25