skip to Main Content

I found this javascript code here, that removes duplicates from an array, but i have a hard time understanding why the condition of the method removes the duplicates, if you give me an answer thank you in advance!

function removeDuplicates(arr) {
     console.log(arr.filter((item,
        index) => arr.indexOf(item) === index));
}

3

Answers


  1. The array checks each item to see if the first instance of itself is at it’s index. This will return true for the first instance of an item, but false for the rest.

    Login or Signup to reply.
  2. If the element is duplicated, there are many elements with that value.

    You will get false for arr.indexOf(item) === index) from the second one. So that element will be removed.

    As a result, the given function will give you an array with only one remaining element for all elements.

    Login or Signup to reply.
  3. Consider an array [1,2,2,3,3,3,3,4]. The filter function will loop through the items in the array starting with item==1, index==1. indexOf() will find a 1 at index position 1, and consider this a matching condition. Next, will be item==2, index==2. This will also pass the "filter" test. So far, so good.

    The next value will be item==2, index==3. The indexOf() function will return the index of the first occurrence of the item in the array. The first occurrence of 2 is at index position 2, not 3, so this item will not be included in the resulting array returned by filter(). Extrapolate this logic, and you can see that only the first occurrence of a given value will meet the true condition of filter().

    The final array of [1,2,3,4] will be output to the console, but the original array will not be altered, and the function removeDuplicates() returns nothing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search