Search code examples
javascriptarraysjsonsortingunderscore.js

Add only unique objects to an array in JavaScript


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 in which 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.


Solution

  • The Underscore findWhere function does exactly what you need - it's not an indexOf search by object identity, but searches objects whose properties have the same values as the input.

    if (_.findWhere(shippingAddresses, toBeInserted) == null) {
        shippingAddresses.push(toBeInserted);
    }