0

I have tried to understand this function :

function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
  }
  
  var a = ['a', 1, 'a', 2, '1'];
  var unique = a.filter(onlyUnique); // returns ['a',1,2,'1']

I wonder how onlyUnique knows about value, index and self being indeed the value, the index, and the array ? Is this related to the filter ?

fransua
  • 501
  • 2
  • 18

1 Answers1

4

As you can see in the MDN docs filter function can take multiple arguments. The rest is purely how javascript functions work.

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}
  
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter(onlyUnique); // returns ['a',1,2,'1']

is simply equivalent to:

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}
  
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter((value, index, self) => onlyUnique(value, index, self)); // returns ['a',1,2,'1']
Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35