ldsmike88 Posted March 15, 2007 Share Posted March 15, 2007 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 More sharing options...
fenway Posted March 16, 2007 Share Posted March 16, 2007 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 https://forums.phpfreaks.com/topic/42919-remove-duplicates-in-array/#findComment-208777 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.