Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add only unique objects to an array in JavaScript

Tags:

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.

like image 323
S16 Avatar asked Jun 27 '13 18:06

S16


People also ask

How do you push data in an array without duplicates?

To prevent adding duplicates to an array:Use the Array. includes() method to check if the value is not present in the array. If the value is not present, add it to the array using the push() method. The array will not contain any duplicate values.

How do you remove duplicates in array of objects in JS?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.


2 Answers

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);
}
like image 161
Bergi Avatar answered Oct 20 '22 08:10

Bergi


Basic example using lodash union method:

var a = [1,2,3];

// try to add "1" and "4" to the above Array
a = _.union(a, [1, 4]);

console.log(a);
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

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.

like image 38
vsync Avatar answered Oct 20 '22 07:10

vsync