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
The Array.prototype.find() method takes a predicate function (a function that returns true or false based on input parameters) and then returns the element provided the predicate is true.
In your case, given the scenario:
var array1 = [1,2,1,3,5,2,3];
var array2 = [1,2,1,3,5,5,3];
function findUnique(array){
return array.find(
// The code below runs for every element of the array.
// - for each element, it takes the element and checks if first position, is the same as last position in the array
(item) => array.indexOf(item) === array.lastIndexOf(item) //
);
}
console.log("For array 1, unique item is: ",findUnique(array1));
console.log("For array 2, unique item is: ",findUnique(array2));
Array.prototype.indexOf(yourArrayElement) returns the position of the first occurrence of yourArrayElement
Oh the other hand, Array.prototype.lastIndexOf(yourArrayElement) returns the position of the last occurrence of yourArrayElement
If yourArrayElement only exists once within the array, the first and last position will be the same and Array.prototype.find() will return that element.
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.
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.