Zepto's use of array.filter

javascript

Solution

`it is creating a new, unique array of elements, right?`

It just filter your array elements to return unique elements.

demo

`But isn't it essentially just cloning the array?`

No as I explain above.

`If so, wouldn't array.slice() be faster?`

Slice doesn't remove duplicates.

`Finally, wouldn't it increase performance to change array.indexOf(item) to array.indexOf(item,idx)? Or better yet, just return true?`

If you only return true you won't identify if the element is duplicated or not.

demo

`When does array.indexOf(item)==idx not equal true?`

Example: I have the following array:

`['10', '20', '30', '20', '10']`

Iterations:

- 1: `array.IndexOf(10) == 0` ? // yes, so return true

- 2: `array.IndexOf(20) == 1` ? // yes, so return true

- 3: `array.IndexOf(30) == 2` ? // yes, so return true

- 4: `array.IndexOf(20) == 3` ? // no because `array.indexOf(20)` is 1 , so return false

- 5: `array.IndexOf(10) == 4` ? // no because `array.indexOf(10)` is 2 , so return false

So, when the element has already been found it gets false because the indexes are not the same.

Problem

I am trying to boost my Javascript understanding, so I've been looking through the Zepto library. I came across this line: ``` uniq = function(array){ return array.filter(function(item, idx){ return array.indexOf(item) == idx }) } ``` What is the purpose of this function? From what I can tell, it is creating a new, unique array of elements, right? But isn't it essentially just cloning the array? If so, wouldn't `array.slice()` be faster? Finally, wouldn't it increase performance to change `array.indexOf(item)` to `array.indexOf(item,idx)`? Or better yet, just `return true`? When does `array.indexOf(item)==idx` not equal true? Is this to prevent duplicate items? But when would that ever actually happen?

Original source