1

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!

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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 });

4 Comments

Sweet thanks! I added an UUID to each JSON object and used the method: if ((_.findIndex(this.cars, {"id": car.id})) == -1) { this.cars.push(car) }
Doesn't this solution still iterate through the collection?
In addition to @FrankModica: Why did you suggest to use lodash while he could use exactly the same function natively? users.findIndex(user => user.id === <variable>). Or even the traditional indexOf...
@developer033 I suggested lodash because that is a library that I find myself using a lot for various common functions that prevent me from having to write my own. It just so happen that it was on my mind when I read his question and suggested it. Even though this one function does exist natively, I hope they find some of the other functions useful in the library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.