I have an array with some elements being "repeats", and I want to delete repeats in the array.
So for example, the list (array) on the left turns into the array on the right:
Ingredients: Ingredients:
Apples Apples
Apples Oranges
Oranges Bananas
Oranges
Oranges
Bananas
What would be a good algorithm to do so?
Right now this is what my psuedocode looks like:
for each element in ingredients (counter j)
for each element-below-current-element (counter k)
if ingredients[i] == element-below-current-element[j]
splice (delete) ingredients[i]
The problem right now though is that I noticed if the original list has an odd number of elements, then I might get something like this:
Ingredients: Ingredients:
Apples Apples
Oranges Oranges
Oranges Oranges
Oranges Bananas
Bananas
Everything works except that I might get a double for one ingredient.
This is my actual code implementation, in javascript and with some angular elements (such as $scope), though it shouldn't really matter.
for(var j = 0; j < $scope.groceryList.length; j++){
for(var k = j+1; k < $scope.groceryList.length; k++){ // for each of elements below current element (j)
if ( $scope.groceryList[j].name == $scope.groceryList[k].name){
$scope.groceryList.splice(k, 1);
}
}
}
Right now what's getting me is how the array length is decreased whenever you remove an array element, which results in your counter jumping one element forward on the next iteration and such...