+ 1

removing dublicates from array please explain me elaborate

what is the process going throught behind var array = [1,2,2,3,4,5] var uniqueArray= array.filter((item, index) => array.indexOf(item)=== index);

14th Jan 2019, 3:46 AM
Danielov
Danielov - avatar
1 ответ
+ 2
daneillonge Starting with the filter(), it is an array method that creates a new array with every element in an array that passes a test. filter() method passes each item/element and index to the anonymous function to be tested and in this case, the test is (array.indexOf(item)=== index). The indexOf() is another array method and it searches the array for an element and returns its position/index if found. If the element is present more than once, the indexOf method returns the position of the [first occurrence(the first match)] The test: Index of the first occurrence of item 1: array[0] equals the index of current item 1: array[0] - true, this item is returned to the new array Index of the first occurrence of item 2: array[1] equals the index of current item 2: array[1] - true this item is returned to the new array Index of the first occurrence of item 2: array[1] equals the index of current item 2: array[2] - false -this item is not Testing continues until every element in the array has been tested. Clear as mud, I bet. https://code.sololearn.com/Wv9uv5uMs9S4/#html
14th Jan 2019, 8:13 AM
ODLNT
ODLNT - avatar