How to use indexOf with filter() in JavaScript

Viewed 13649

This is the code I found as an answer to this question: Write a JavaScript program to remove duplicate items from an array (ignore case sensitivity).

var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3, 'A'];

var uniqueArray = arr1.filter(function(elem,i,rep){
    return i == rep.indexOf(elem);
})
console.log(uniqueArray);

I know what filter() does and that indexOf is used to find the index of the first occurence of an element, but I don't understand how this line:

i == rep.indexOf(elem);

introduces only the unique elements to uniqueArray.

7 Answers

var arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3, 'A'];

var newArray = 
 arr1.filter(
  (obj,index,array)=> {return array.map(el => el).indexOf(obj) == index}
            );
  
console.log(newArray);

var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3, 'A'];

var uniqueArray = arr1.filter(function(elem,i,rep){
    return i == rep.indexOf(elem);
})
console.log(uniqueArray);

Let me try to explain the code and its result .

The Array.prototype.filter can take three arguments . In your code ,

  1. elem is an element of the Array arr1.
  2. i is the index of elem in the arr1.
  3. it has an index in arr1 .
  4. rep is the same Array as arr1. Just consider rep as arr1.

According to [MDN's article][1] indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Now we can try to understand what the code does .

  1. if we suppose that the value of elem is 'a' , rep.indexOf(elem); will return 1.
  2. Suppose that elem is 'a' and the index of elem i is 3 , return i == rep.indexOf(elem); will return false and will return true when i the index is equal to 1.

That means the the filter will return an array with the values of what is in the first index of each element in the Array.

Let simulate the code :

var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3, 'A'];

var uniqueArray = arr1.filter(function(elem,i,rep){
    console.log("index  :"+i+" first indext of this value: "+rep.indexOf(elem)+" element :"+elem+ " is filterable :"+(i == rep.indexOf(elem)) );
    return i == rep.indexOf(elem);
})
console.log(uniqueArray);

Related