-1

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

4
  • 2
    Did you read the documentation for filter? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 4, 2022 at 17:44
  • index is the position of item in array Commented Aug 4, 2022 at 17:47
  • stackoverflow.com/questions/50854750/… Commented Aug 4, 2022 at 17:47
  • The index won't help much for determining unique elements. Walk through the input array, keeping track of numbers you've seen by adding them to a set. For each number, push it to the output if it's not in the set or ===1. Then add it to the set Commented Aug 4, 2022 at 18:16

2 Answers 2

1

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

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

7 Comments

So with array.filter((item, index) => array.indexOf(item) === index), if we let array = [1, 1, 2], the inputs for (item, index) are (1, 0), (1,1), (2,2)?
In this case you are not printing anything if you wanted that result you would have to make a console.log(item, index)
Array.filter make a new array if the item pass the test in this case all of them would have passed the test, if you stored the returned value in a variable you would ended up with the same array
how does all of them pass the test? the only pair that works is (1,1)?
Because array.indexOf(item) === index returns true so it pass in the test
|
0

Try this code:

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

It basically iterates through each item and its index.

2 Comments

so like (a,0) then (b, 1) then (c, 2)?
Exactly, you can try it your own in a console. jsconsole.com

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.