vgogov
vgogov

Reputation: 77

Angular2 avoid adding duplicate JSON objects to array

I'm trying to avoid adding duplicate objects to an Angular2 array. For example let's say we have an array "Cars" and we put in a JSON object in that array that might be something like:

{
 "brand": "Acura"
 "engine": "2.4L"
 + others details
}

We can keep adding cars with to the array. My issue is now how to avoid adding the same car into the array again. If I were to add the same JSON as described above, it shouldn't be added. Would I have to iterate through all the existing objects in the array and compare each field of the JSON? This sounds like an expensive operation to me, or is there some more elegant/faster method?

Thanks!

Upvotes: 1

Views: 509

Answers (2)

jLee
jLee

Reputation: 483

You need to find or create a unique property on the items in the list, then you could use something like lodash to query the array by a property to see if that item already exists in the list before you add it.

Example from Lodash site

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });

Upvotes: 0

Frank Modica
Frank Modica

Reputation: 10516

If each car has something unique about it (like an ID), you could use an object instead of an array:

var map = { };

function add(car) {
    if (map[car.id]) {
        return;
    }

    map[car.id] = car;
}

Your ID could be something else unique, like a combination of the brand and year or something similar.

map[car.brand + car.year] = car

Upvotes: 4

Related Questions