In this lesson you will learn how to remove duplicates from the flat array which is a common coding challenge for beginner JavaScript interviews.
We will learn how to write a duplicate removal function using functional programming approach with filter. The array filter method allows you to create a new array out of elements that pass a certain condition within the filter. You'll see how we can use indexOf
to filter out any duplicates.
Instuctor: [0:00] Another way of removing duplicate values from array is using the filter function from NativeArray methods. Let's see what we can do with filter const. Filter func. We want to get an array and then to do some tricky thing.
[0:23] We want to filter. In the filter callback, we want to grab item and index. Then we want to look in the initial array for the index of the item and see that it's equaling to index of the current iteration. Let's log filter function and pass a basket to it.
[1:06] You see that it's actually working. Let's quickly go through how it works. The filter just iterates over all the values in the basket. It finds apple. The index of apple would be . The index which is current index, coming from this argument callback, is also equaling . They are the same.
[1:33] We let the item go into our final array. Same for pear, but now with index 1. Same for pineapple, now with index 2. When we come to this apple, the array index of item would be , because the index of returns the first found index of the item in the array.
[1:57] The current index is , 1, 2, 3, which is not equaling to zero. Which means that this item won't go into our final array. The same goes for pear. The index of pear would be 1, because index of returns the first found item again, which would be with index 1. Our current index of the iteration would be , 1, 2, 3, 4 of this particular pear.