-2

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

  • 2
    Did you read the documentation for filter? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – epascarello Aug 04 '22 at 17:44
  • `index` is the position of `item` in `array` – Chris Li Aug 04 '22 at 17:47
  • https://stackoverflow.com/questions/50854750/how-to-find-non-repeated-numbers-in-an-array-using-javascript – epascarello Aug 04 '22 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 – danh Aug 04 '22 at 18:16

2 Answers2

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

  • 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)? – mathsnerd22 Aug 04 '22 at 18:05
  • In this case you are not printing anything if you wanted that result you would have to make a console.log(item, index) – Filinto Delgado Aug 04 '22 at 18:16
  • 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 – Filinto Delgado Aug 04 '22 at 18:17
  • how does all of them pass the test? the only pair that works is (1,1)? – mathsnerd22 Aug 04 '22 at 18:19
  • Because array.indexOf(item) === index returns true so it pass in the test – Filinto Delgado Aug 04 '22 at 18:23
  • This condition seems trivial to me array.indexOf(item) === index, wouldn't the LHS equal to the RHS always since they're both ways of saying the same thing? – mathsnerd22 Aug 04 '22 at 18:35
  • In the first iteration we have item = 1 and index=0 so array.indexOf(item) is equal to 0, 0 === 0 so it returns trur – Filinto Delgado Aug 04 '22 at 19:06
-1

Try this code:

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

It basically iterates through each item and its index.