I read the book Pro Angular. I do not understand the meaning of the entry in the function .filter (...)

get categories(): string[] { return this.model.getProducts() .map(p => p.category) .filter((category, index, array) => array.indexOf(category) == index);} 

I know that this is a filtering function in an array, but why check a known element index?

    1 answer 1

    In this case, this is an example of obtaining unique values ​​in an array:

    .indexOf checks elements from the beginning of the array, and if there are several identical elements in the array, then in this case the index will match only for the first occurrence:

     var a = [1, 1, 2, 2, 3, 3, 4, 4]; console.log(a.filter((cur, i, arr) => arr.indexOf(cur) === i)); 


    However, this may not work with objects, since in this case the two objects will be considered different, despite the fact that they have the same values ​​in the fields

     var a = [{ a: 1 }, { a: 1 }, { a: 1 }]; console.log(a.filter((cur, i, arr) => arr.indexOf(cur) === i)) 

    In this case, it is better to use the findIndex method findIndex

     var a = [{ a: 1 }, { a: 1 }, { a: 1 }]; console.log(a.filter((cur, i, arr) => arr.findIndex(c => ca === cur.a) === i))