0

Regarding this post (Remove Duplicates from JavaScript Array) on creating a new array of unique values from another array.

Code in question:

uniqueArray = myArray.filter(function(elem, pos) {
    return myArray.indexOf(elem) == pos;
})

Using this as the test data:

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

Desired result is an array with only unique values:

var unique_names = ["Mike","Matt","Nancy","Adam","Jenny","Carl"];

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:

  1. Is myArray.indexOf("Mike") the same as 0? Yes, so add "Mike" to the new array.
  2. Is myArray.indexOf("Matt") the same as 1? Yes, so add "Matt" to the new array.
  3. 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.

Community
  • 1
  • 1
jason
  • 4,721
  • 8
  • 37
  • 45
  • 5
    `indexOf` returns the position of the first matching element in the array. When you're processing the second Nancy, the found position differs from the currently processed index, hence `false`. – Rob W Mar 29 '13 at 20:39
  • Check my answer here http://stackoverflow.com/questions/13945965/zeptos-use-of-array-filter/13946124#13946124 – elclanrs Mar 29 '13 at 20:41

2 Answers2

1

The indexof is the index of the first appearance of the element, so the second Nancy would get the index of the first Nancy, and would be filtered out.

Iftah
  • 9,512
  • 2
  • 33
  • 45
1

6) Is myArray.indexOf("Nancy") the same as 5? No (it's 2, just like it step 3), so skip the duplicated "Nancy".

indexOf gives you the first occurrence of the item.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171