I solve a coding problem on codewars site.
Then I saw the solution of the community and I read the most clever solution but I did not understand it.
So please I need an explanation for that code
This is the code so far:
const removeDuplication = a => a.filter( v => a.indexOf(v)===a.lastIndexOf(v) ) ;
Idea #2: Filter takes an array of things, and for each item, wants a true or a false. If it’s true, it keeps the item, otherwise it throws it away in the result.
Idea #3: indexOf starts at the beginning of an array, finds the first instance of the target, and reports back the index.
lastIndexOf does the same thing, but from the end of the array.
Question: What does those two values being equal mean, in terms of an array?
Well, let me see if i can give an example, and you see when it makes sense.
Let’s say I tell you the following:
Start at this end of the street. Walk down the street until you come to a stop sign; then stop. (If you don’t encounter a stop sign, stop after you reach the other end of the street.)
When you’ve stopped, what can you tell me for absolute certainty about the bit of the road behind you?
Extra hint for that first one: How many stop signs are behind you?
Same situation, but this time you and I both do the same thing, but from opposite ends of the street. What can we both say about what is behind each of us?
Do it again; If we both stop at the exact same point, what can we say about the entire road, keeping in mind there is no space between us?
And because eventually someone’s going to say “I still don’t get it”… if you really feel like spoiling yourself, here’s the final idea:
If there are no stop signs behind you, and no stop signs behind me, and we’re both standing at the same point, there are no stop signs on the road except the one stop sign that we’re standing at. There is exactly one stop sign on the road; if there were more than 1, one of us would have stopped sooner.
As there seems to be some language barrier going on here, explaining it in more concrete terms might help.
The indexOf method gives the first index of something, and lastIndexOf gives the last index of something.
When there are multiples of something, indexOf and lastIndexOf will give different locations.
For example with the letter “m” in the the name “abdulrahmanmhdanas”. indexOf(“m”) gives the 9th position, and lastIndexOf(“m”) gives 13.
When the first and last positions are different, you know that there is more than one of that thing.
When the first and last positions are the same, you know that there is only one of that thing.
An example of when the positions are the same is with indexOf(“r”) and lastIndexOf(“r”) in “andulrahmanmhdanas”. In both cases you get the 6th position, which tells you that the letter “r” is unique in that name.