Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use indexOf with filter() in JavaScript

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.

like image 845
Nicolae Stroncea Avatar asked Aug 05 '17 13:08

Nicolae Stroncea


3 Answers

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);

here elem would contain each element of the array, i would be the index of the current elem and rep would contain the whole array
now rep.indexOf(elem); would always give the index of the first occurrence of the element now Array.prototype.filter() works in a way that if you return true, it would not filter it but if you return false, it would filter it out so every element except the first occurrence gets filtered out

like image 61
marvel308 Avatar answered Sep 28 '22 08:09

marvel308


According to MDN's article about Array#indexOf:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

In the code you've presented:

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

The variable i in the filter's callback is the index of the current item in the array. If there is more than one appearance of an item, the current index (i), and the index returned by Array#indexOf would be different for duplicated values after the 1st. In this case the filter callback will return false, and the duplicated value will be filtered out.

like image 26
Ori Drori Avatar answered Sep 28 '22 08:09

Ori Drori


i == rep.indexOf(elem);

will always return the first index under which the element has been found in the array, so only the first of any copies will be accepted in the filtered array.

like image 37
Carsten Massmann Avatar answered Sep 28 '22 08:09

Carsten Massmann