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 Answers 2
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;
}
5 Comments
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
Explore related questions
See similar questions with these tags.
array2had{name:'jill'}in position 4, would that match fail, since it's in position 1 inarray1? Or would it succeed since it's inarray2somewhere?