I already found the solution here by OhJeez: How to get an array of unique values from an array containing duplicates in JavaScript?
array.filter(function() {
var seen = {};
return function(element, index, array) {
return !(element in seen) && (seen[element] = 1);
};
}());
What I want to ask is how to make sense of the code above. The part I don't understand is how does var seen keep its keys. Wouldn't each iteration reset seen back to an empty hash/object?
Edit: I think I understand how closures work, and that does not solve my question. To my understanding, Array.prototype.filter loops each element of the array to the callback function, in this case the anonymous function 'var seen = {}; return function(element, index, array) {return !(element in seen) && (seen[element] = 1);};. This in turn returns the function inside.
My question, again, is shouldn't each iteration run the line 'var seen = {}'? Then how could seen keep its elements?