1

Let's imagine I have this array:

bucket.bucketList =[];

bucket.addItem = function(item) {
  bucket.bucketList.push(item);
}

The function pushes an object called foo this into the array on every mouse-scroll:

Some foo's also have a property , foo.name = "something";

The question is, what is the best way to delete All duplicates based on their name property names whilst keeping the most recents one pushed in?

I am using jQuery already in my project, so if jQuery has a more elegant way of doing this than vanilla JS i'd be more than happy to use it.

0

1 Answer 1

2

This code removes all duplicate names, keeping the last one in the array.

You can traverse backwards through the array and remove any items with a name that you've already seen, using an object to keep track of the names you've already seen. By traversing backwards, you keep the last one and you don't have to do any array index corrections when you remove the current entry from the array:

var dict = {}, item;
for (var i = bucket.bucketList.length - 1; i >= 0 ; i--) {
    item = bucket.bucketList[i];
    if (item.name) {
        // if already in the dict, remove this array entry
        if (dict[item.name] === true) {
            bucket.bucketList.splice(i, 1);
        } else {
            // add it to the dict
            dict[item.name] = true;
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Are you iterating over the array backwards here?
@NicholasKyriakides - yes, it's a backwards iteration for two reasons. 1) The OP wants to keep the last item of a dup so going backwards makes that easier because you see the last one first. 2) When you remove elements from the array with a backwards iteration, you don't have to correct your indexing like you do if you iterate forwards.
@Thanks, I am guilty of code copy-paste and now I am trying to rectify my mistake - I am the OP.

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.