You could try filtering all element that their indexOf
and lastIndexOf
are the same value, meaning it only has one occurance in the array.
const arr= [100, 123, 100, 122, 119, 203, 123, 76, 89]
const removeNo = (data) => {
return data.filter((val) => data.indexOf(val) === data.lastIndexOf(val));
}
console.log(removeNo(arr))
Explain
indexOf
searches the index an element from the left side of an array, while lastIndexOf
searches starting from the right side.
Imagine an array, that we want to find all elements without duplicates.
[1, 2, 3, 1, 2]
Using filter
function, we are iterating every element throughout the array.
- On the first iteration, it checks the first array which is
1
[1, 2, 3, 1, 2]
^ <- filter pointer
- Then
indexOf
searches 1
from the left side, which is also the first element
[1, 2, 3, 1, 2]
^
^ <- indexOf pointer
- Since it found the target element from the left side, now it's time to find the same element
1
from the right side with lastIndexOf
, which is the fourth element
[1, 2, 3, 1, 2]
^
^
^ <- lastIndexOf pointer
Counting from the left side, 1
is found on the first position. But while counting from the right side, 1
is found on the fourth position. Which does not match the previous search, so the first element 1
fails the test.
The second element also fails the test due to the same reason.
[1, 2, 3, 1, 2]
^ <- filter pointer
^ <- indexOf pointer
^ <- lastIndexOf pointer
- While on the third iteration, both searches lands on the same index, so it is confident to say
3
is unique in this array.
[1, 2, 3, 1, 2]
^ <- filter pointer
^ <- indexOf pointer
^ <- lastIndexOf pointer
- Then the rest of the elements also fail the test using the same logic.
[1, 2, 3, 1, 2]
^ <- filter pointer
^ <- indexOf pointer
^ <- lastIndexOf pointer
[1, 2, 3, 1, 2]
^ <- filter pointer
^ <- indexOf pointer
^ <- lastIndexOf pointer
- So only the third element
3
passes the test, the output is [3]
.
Hope this helps you understanding this approach.