Sorted Union: filter() with index as argument

Hello,
Sorted Union
Could you give me an explanation about:

 uniqueArray = concatArr.filter(function(item, pos) {
    return concatArr.indexOf(item) == pos;
  });

In this code:

function uniteUnique() {
  var concatArr = [];
  var i = 0;
  while (arguments[i]) {
    concatArr = concatArr.concat(arguments[i]);
    i++;
  }
  uniqueArray = concatArr.filter(function(item, pos) {
    return concatArr.indexOf(item) == pos;
  });
  return uniqueArray;
}

// test here
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

I never seen using the index argument in a filter callback until now. My problem is I think that concatArr.indexOf(item)will be always egal to his pos.
Where is my mistake ?

If we are on the second instance of a given value within an array, the indexOf for that particular value would be the first instance. For example:

const arr = [1,2,4,1,5,2,1]

For the first three values, you’re right. On the fourth, item===1 and pos===3 - but what is the arr.indexOf(1) ?

Oh! yes, thanks you.

1 Like

Because indeOf() return the first position only :wink:

1 Like