Z
Z
zlodiak2018-05-12 13:50:15
typescript
zlodiak, 2018-05-12 13:50:15

How does the distinct counterpart work?

Here
https://stackblitz.com/edit/angular-2ic5vr
reproduced an example from a book who would like to understand how it works in detail.
I'm only interested in one line in the product.repository.ts file:

.filter((c, index, array) => array.indexOf(c) == index);

The input contains an array of category names. In it, some categories are repeated several times. At the output, we have the same array, but in which the category names do not repeat.
First of all, I don't understand why there is a comparison with index. I present how the filter() operator works.
Please explain with your fingers what is happening in this line.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-05-12
@zlodiak

First of all, I don't understand why there is a comparison with index.

Then, that this comparison for a specific value will produce trueexactly once - since it indexOfreturns the first index by which you can find an element equal to the specified one. That is, if indexOfthe current element is equal to the current index, then the element is encountered for the first time, and it should be left.

F
forspamonly2, 2018-05-12
@forspamonly2

I don’t know what kind of book you have there that offers examples of algorithms with quadratic complexity, but for real projects it’s better not to write like that. do something through sets:
Array.from(new Set(sourceArray]))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question