Inside the Chrome Console I have a string:
var string = 'john, john, bob, nina, colin, bob, luck, robert, nina, john, jack';
Then it is being modified and assigned to a new value using two, seeming identical to me, methods:
First method:
var string2 = string.split(", ").filter(function(value, index, array){
return index === array.indexOf(value);
}).join(', ');
Second method:
var string3 = string.split(", ").filter(function(value, index, array){
if(index === array.indexOf(value)) return index;
}).join(', ');
What should both methods do:
- Turn the string into an array of each word separately.
- Filter the array so that no duplicate values exist.
- Turn the array back into a string format.
What I would expect values of string2 and string3 to be :
"john, bob, tony, nina, colin, luck, robert, jack"
They should be strictly identical (based on my logic).
What I actually get:
string2 = "john, bob, tony, nina, colin, luck, robert, jack";
string3 = "bob, tony, nina, colin, luck, robert, jack"
"John" is missing in the second string.
What I already checked:
- The strict comparison (===), that is being performed inside the if-statement () is true for the first "john".
- Both index (parameter of the function) and index of the value of the first "john" are 0 as expected.
What I ask:
Explain, please, why do the results differ?