Question

I cant wrap my head around this one. can someone show me an example of a function that does this. I need a javascript function that will do this

if all of array1s values matches array2s values return true if there is no/partial match return array1s values that did not match

array1 = [{name:'joe'},{name:'jill'},{name:'bob'}]
array2 = [{name:'joe'},{name:'jason'},{name:'sam'}]

match(array1, array2) 

//if fails returns [{name:'jill'}, {name:'bob'}]
//if success returns true

please help my brain hurts XD

Thanks

EDIT: Sorry for not saying this before the objects would have a few other property that wouldnt be the same. so a given object could look like

array1x = [{name:'joe', id:33},{name:'jill'},{name:'bob'}]
array2x = [{name:'joe', state:'fl'},{name:'jill'},{name:'bob'}]

i need to match just the name property within the object

Was it helpful?

Solution

Array.prototype.filter() + Array.prototype.some() =

function match(arr1, arr2) {
    var notFound = arr1.filter(function(obj1) {
        return !arr2.some(function(obj2) {
            return obj2.name == obj1.name;
        });
    });

    return !notFound.length || notFound;
}

fiddle

OTHER TIPS

Here is a very basic example of such function:

function match(array1, array2) {
    var len = Math.max(array1.length, array2.length),
        result = [];

    for (var i = 0; i < len; i++) {
        if (JSON.stringify(array1[i]) !== JSON.stringify(array2[i])) {
            result.push(array1[i]);
        }
    }

    return result.length > 0 ? result : true;
}

It will compare the serialised elements as they go one-by-one considering index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top