Home > database >  Find a unique number in an array
Find a unique number in an array

Time:05-20

Can someone explain to me what exactly is this line of code doing?

function findUniq(array) {
  return array.find((item) => array.indexOf(item) === array.lastIndexOf(item))    
}

I want to know what this line is exactly doing:

return array.find((item) => array.indexOf(item) === array.lastIndexOf(item))

What I think is happening here is that for every item inside the array it is comparing the first index of that item to the last index of item. it returns the items that equal to eachother.

I don't understand how it is returning the unique array.

If I were to write this function it would be like this:

return array.find((item) => array.indexOf(item) != array.lastIndexOf(item))

However, that doesn't work since it is returning the common number.

thanks

CodePudding user response:

indexOf returns the first found position of the given element in the array whereas lastIndexOf returns the latest position of the given element in the array.

If indexOf === lastIndexOf, it means the first found element is the same as the latest one --> the element is unique in the array.

CodePudding user response:

The reason that it return a unique number, because the find function loop from the start and from the end on each iteration, so if the index of both indexOf that loops from the start and lastIndexOf that loops from the end is equal it's mean that there are no duplicates across the array beside the current item.

  • Related