I'm struggling with the following piece of code that filters an array with repeated items but keeps the non-repeated items.
temp = temp.filter((a, _, aa) => aa.indexOf(a) === aa.lastIndexOf(a));
(a, _, aa)
The underscore in the argument list is just passed as a placeholder. It's commonly used to signal an argument that's thrown away and never used but needs to be there as a placeholder. Essentially a "dummy" variable.1
In this case,
Array.prototype.filter takes in a callback with three arguments. Since the author of the code wants access to the array which
filter is being called on but doesn't care about the index, they must supply a second argument nonetheless to use the third, array argument. Note that
_ is just like any other variable, and you can still do whatever you do to a variable with it. It's just been commonly used as a throwaway variable.
If you wanted an explanation of the code, it just iterates through the array and checks the current element's index. The callback returns true if
a (the current element being processed)'s index in
aa (the array
filter is being called on) is the last index the element appears. If it is, that means the element occurs nowhere else in the array, and thus filters out duplicate elements.
By "commonly used" I mean that many languages adopt this practice. In languages such as Python, it's a well-known standard. Other languages such as SQL, Haskell, and Scala use this to (although Haskell as a pattern).