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
https://forums.phpfreaks.com/topic/42919-remove-duplicates-in-array/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.