Home > Net >  How does array.filter((item, index) => array.indexOf(item) === index) work?
How does array.filter((item, index) => array.indexOf(item) === index) work?

Time:08-05

How does array.filter((item, index) => array.indexOf(item) === index) work?

I'm aware the that filter method iterates over all the items in the array, but how does this method work when you add in index as a parameter too? Does it then iterate over entire set of pairs of (item, index)?

I'm trying to find the unique element in an array in which every element is duplicated apart from one. e.g. [1,1,2], [1,2,3,2,1], etc

CodePudding user response:

When you add an index the index parameter will be the index of the element that the iteration is happening on, for example:

const myArray = [a, b, c]
myArray.filter((item, index) => {console.log(`The item ${item} is on index ${index} on the array`)}

That will print

$ The item a is on index 0 on the array
$ The item b is on index 1 on the array
$ The item c is on index 2 on the array

See more infromatiom on MDN page for filter

CodePudding user response:

Try this code:

['a','b','c'].filter((item, index) => console.log(item, index))

It basically iterates through each item and its index.

  • Related