I have the following function, which pretty much does what it supposed to, but I would like to understand exactly what it does on each steps of its loop.
Could you please take a look to the function below and give me a clear explanation commenting each step or the Filter and IndexOf methods?
Thank you very much in advance.
var arr = [6,2,6,8,9,9,9,4,5];
var unique = function(){
return arr.filter(function(e, i, a) {
return i === a.indexOf(e);
})
}
unique();
indexOf
returns the first index of an element in an array:So if you use
filter
as in your example when it gets to the second occurance of an element the index (i
in your example) will not be equal to the value returned byindexOf
and be dropped. In my array above the second 2 is at position 2 which obviously doesn't strictly equal the one returned byindexOf
.The end effect is that any duplicate elements get dropped from the copy returned by
filter
. And it is a copy, the original array is not mutated.EDIT
I should probably mention that recent versions of JavaScript give us a better way:
If log the values like:
you will get:
and so on...
e = current element from array, i = index of the array, a = array source;
Filer function: "The filter() method creates an array filled with all array elements that pass a test (provided as a function)."
indexOf: "The indexOf() method searches the array for the specified item, and returns its position."