Jump to content

Remove Duplicates in Array


ldsmike88

Recommended Posts

I have this really long array that I run through a function I made to remove the duplicates. The only problem is it removes all of them but one... I can't figure out why. If I run the removeDuplicates function a second time it works, but not the first time. Anyone know why?

 

Array = Websites, Games, Soups, Soups, Church, Church, Games, Church, Church, Church, Church, Websites, Church, Church, Church, Church, Soups, Church, Church

 

If you notice there are a whole lot of values that are Church. Guess which one doesn't get removed.

 

function removeDuplicatesTWO(array){
for(i = 0; i < array.length; i++){
	for(a = 0; a < array.length; a++){
		if(i != a){
			if(array[i] == array[a]){
				array.splice(a, 1);
			}
		}
	}
}
return(array);
}

 

Running it through this function and sorting it will return:

Array = Church, Church, Games, Soups, Websites

Link to comment
Share on other sites

The preferred way to do this is to built a hash from the array... or as an alternative, if you want to the order to stay the same, to simply "mark" the elements as duplicates based on a seen hash in a parallel array.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.