How can I check for the existence of an object in an array in javascript?
Here is a simple example. Let's say I have an array that looks like this:
let array = [{"zone": "WV", "zip": "56855"}, {"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}]
And now I want to add an object to my array
but only if it doesn't already exist.
For example attempting to add this object would fail:
let addMe = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}]
But this would succeed
[{"zone": "SC", "zip": "55555"}, {"zone": "TN", "zip": "88888"}]
Obviously addMe
is an array that would need to be stepped thru, failing on some objects, succeeding on others.
I am trying to use filter
but its not working like I want. And I'm having to step thru the original array as well as step thru the object I'm trying to add, creating nested for loops which is confusing as hell. This is my attempt:
array.filter(function(item){ addMe.forEach(function(element){ if(item.zone != element.zone && zone.zip!= element.zip){ array.push(element); } }); });
Is there a better way?
hashing data structure
what's that? I found this.. is this along the lines of what you're thinking? medium.freecodecamp.org/…