I have task to receive unique element in order from string as parameter. I do not understand how this function uniqueElements returns [\'A\',\'B\',\'C\',\'B\']
var uniqueElements = function(word) {
return [].filter.call(word, (function(elem,index) {
return word[index-1] !== elem
}));
}
is equivalent to
var uniqueElements = function(word) {
return word.split("").filter(function(elem,index) {
return word[index-1] !== elem
});
}
which should already be clearer: it turns word into an array of char then filters every char that is different from the previous one. This explains why "B" is present twice in the result.
To get unique elements, you can do
var uniqueElements = function(word) {
var res = []
word.split("").forEach(function(val){
if (res.indexOf(val)===-1) res.push(val);
});
return res
}