0

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

2
  • Are you trying to match by position? For example, if array2 had {name:'jill'} in position 4, would that match fail, since it's in position 1 in array1? Or would it succeed since it's in array2 somewhere? Commented Mar 20, 2014 at 18:09
  • No i don't want the position to be a factor. thanks for your commit below by the way. Commented Mar 20, 2014 at 19:31

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

An abstraction of this technique keeps your nice algorithm but lifts the test of whether the two objects match into a callback function.
Worked perfectly! thank you XD and @ScottSauyet nice way to make it modular/reusable :-)
I think return !array2.some(function(obj2) { Should be return !arr2.some(function(obj2) { right?
@codenamejames You're right! I've fixed the typo :)
I would add another parameter to the match function with the name of the property name to check for to make it more usable: function match(arr1, arr2, id) { ... return obj2[id] == obj1[id];
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.