I have read through a number of Stack Overflow questions but none appear to be relevant to the problem I'm trying to solve.
I have an array of objects that I'm saving in localStorage which looks like this (this example includes just two):
[
{
"image": "http://example-image.jpg",
"restaurantName": "Elena's L'Etoile",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address1"
},
{
"image": "http://example-image2.jpg",
"restaurantName": "Pied a Terre",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address2"
}
]
Each time a user visits a page, data is pulled from the page, and a restaurant object is created which looks like this:
var restaurant = {"image": $image, "restaurantName": $restaurantName, "parentLocation": $parentLocation, "areaLocation": $areaLocation, "pageLink": $pageLink};
This is then stored pushed into the existing array of objects (above) with:
existingRestaurants.push(restaurant);
The problem is that if the user visits the same page twice, duplicate objects are pushed in the array. How can I ensure that only unique objects are pushed into the array?
Approaches I've looked into: using $.each, $.inArray, $.grep. I thought that the simplest way would be to loop through all the objects in the existingRestaurants array and compare the value of the "restaurantName" key with the corresponding value in the new restaurant object.
But I haven't been able to find anything else similar on Stack Overflow.
$.grep
or$.each
so we can help point out problem. You were probably trying to compare two objects that don't share same reference.$.inArray
would definitely not work for this.filter
or.some
could be used to check if the object already exists. No need for jquery related stuff. some