How does this snippet for removing duplicates from an array work

FlashGordon

New Member
Regarding this post (Remove Duplicates from JavaScript Array) on creating a new array of unique values from another array.Code in question:\[code\]uniqueArray = myArray.filter(function(elem, pos) { return myArray.indexOf(elem) == pos;})\[/code\]Using this as the test data:\[code\]var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];\[/code\]Desired result is an array with only unique values:\[code\]var unique_names = ["Mike","Matt","Nancy","Adam","Jenny","Carl"];\[/code\]Where I'm at:I understand that filter will run a function on each member of the array, and that elem is the element being reviewed, and that pos is its index. If something causes that function to return false, then that element will not be included in the new array. So walking through it, this happens:[*]Is myArray.indexOf("Mike") the same as 0? Yes, so add "Mike" to the new array.[*]Is myArray.indexOf("Matt") the same as 1? Yes, so add "Matt" to the new array.[*]Is myArray.indexOf("Nancy") the same as 2? Yes, so add "Nancy" to the new array.[repeat for all elements. All pass.]Basically I don't get why the 2nd Nancy would evaluate to false.
 
Back
Top