Let's say I start with this:
var shippingAddresses = [{
"firstname": "Kevin",
"lastname": "Borders",
"address1": "2201 N Pershing Dr",
"address2": "Apt 417",
"city": "Arlington",
"state": "VA",
"zip": "22201",
"country": "US"
}, {
"firstname": "Dan",
"lastname": "Hess",
"address1": "304 Riversedge Dr",
"address2": "",
"city": "Saline",
"state": "MI",
"zip": "48176",
"country": "US"
}];
I use this to prepopulate a form. Users can edit entries or add new ones. I need to prevent them from adding duplicates.
The issue is that the structure of the form that I am serializing and the order these values are returned from the database are not the same, so there is a chance that I will insert an item into this array with the following format:
{
"country": "US",
"firstname": "Kevin",
"lastname": "Borders",
"address1": "2201 N Pershing Dr",
"address2": "Apt 417",
"zip": "22201",
"city": "Arlington",
"state": "VA"
}
Which is the same as the first entry, just ordered differently.
I am loading underscorejs, so if there's a way to handle it with that library that would be great. I'm also using jQuery if that helps.
At this point I'm not sure how to proceed.
Basic example using lodash union method:
While this doesn't directly answers the question, it does answers the broader question of how to add unique values to an Array, and like myself, others might stumble upon this page from google.
EDIT, this will work with your example of unsorted properties:
and we could do this with a one-liner but it would be super ugly:
The Underscore
findWhere
function does exactly what you need - it's not anindexOf
search by object identity, but searches objects whose properties have the same values as the input.If you want to check the user input object you could try this function:
And try to invoke this check function in different parameter (uniqueInput and duplicatedInput) I think it could check the duplication input in your shipping addresses.
I make a jsfiddle. You could try it. Hope this is helpful for you.
based on this answer to: "js-remove-an-array-element-by-index-in-javascript"
https://stackoverflow.com/a/7142909/886092
I'm using the following idiom that is concise and does not require underscore.js or any other framework.
Here is an example for recording selected and deselected rows for DataTables jquery plugin. I keep an array of currently selected ids, and I don't want to end up with duplicates in the array:
in coffeescript
More generally it would
or in JS