5

I am trying to understand the 3-parameter filter function in Javascript. What is this piece of code doing? (I am currently refactoring existing code in system.)

docs = _.cloneDeep(docs.filter((v, i, a) => a.findIndex(t => (t.documentNumber === v.documentNumber)) === i));
2
  • v = current element, i = index of current element, a = is the original array. this code seems checking to itself. Commented Jul 21, 2020 at 4:58
  • Since you are using lodash anyway, you might consider rewriting this as _.cloneDeep(_.uniqBy(doc => doc.documentNumber)). Commented Jul 22, 2020 at 5:49

2 Answers 2

5

The callback for filter is given three arguments, the current element, the index, and the original array.

The code you provided creates an array with unique documentNumber properties, as for each element, it looks for the index of the first element that has the same documentNumber as it; if the index of the found element is the same as the current index, then this element is the first occurrence of that property in the array and only then will the callback return true which retains the element. It will remove duplicates.

See also: Array#findIndex

Sign up to request clarification or add additional context in comments.

3 Comments

That's a good explanation of some rather obscure code
That's all there is to it. It may look intimidating at first, but after breaking it down, it becomes a lot easier to understand.
This is one of the easiest ways to remove the duplicates. One can also use a Set.
2

It filters to the first instance of unique a documentNumber

const docs = [
  { documentNumber: 1 },
  { documentNumber: 1 },
  { documentNumber: 2 },
  { documentNumber: 3 },
  { documentNumber: 4 },
  { documentNumber: 4 },
  { documentNumber: 4 },
  { documentNumber: 5 },
  { documentNumber: 6 },
  { documentNumber: 7 },
  { documentNumber: 7 },
  { documentNumber: 1 },
  { documentNumber: 8 }
];

let results = docs.filter((v, i, a) => a.findIndex(t => (t.documentNumber === v.documentNumber)) === i);
console.log(results);

3 Comments

how have you written it by the way to remove duplicates?
It is the function you have in your question, I am just demonstrating what it does.
Because findIndex returns the first instance where where the documentNumber is equal to the current item being filtered only the first instance of any documentNumber will be in the final results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.