admin管理员组文章数量:1312836
Can someone explain how this piece of code works? The output is a vector with the letters of input but without repetition.
var uniqueInOrder = function (iterable) {
return [].filter.call(iterable, (function (a, i) {
return iterable[i - 1] !== a
}));
}
console.log(uniqueInOrder("aaaaaBBBDSJJJJ"))
Can someone explain how this piece of code works? The output is a vector with the letters of input but without repetition.
var uniqueInOrder = function (iterable) {
return [].filter.call(iterable, (function (a, i) {
return iterable[i - 1] !== a
}));
}
console.log(uniqueInOrder("aaaaaBBBDSJJJJ"))
Share
Improve this question
edited Oct 3, 2015 at 13:02
thefourtheye
240k53 gold badges465 silver badges500 bronze badges
asked Oct 3, 2015 at 12:16
daymosdaymos
2033 silver badges8 bronze badges
2 Answers
Reset to default 5Let's break this down:
return [].filter.call(iterable,(function (a, i) { return iterable[i - 1] !== a }));
*. we are returning an Array.
*. using .filter.call(iterable,
allows us to use the Array.prototype.filter
method on the iterable
which is a string (making the function treat the string as an array of chars) as the first parameter that call
gets is the context.
*. the filter function returns a subset of the array for each element that returns true. so when doing return iterable[i - 1] !== a
every time we check if the element in index i-1
which is basically the previous element is not equal to the current element which is a
if it is not equal we return true so the a
element is a part of the subset array which is being returned.
note that the easiest way for you to understand is debug just paste this code in the developer toolbar console:
var uniqueInOrder = function (iterable)
{debugger;
return [].filter.call(iterable,(function (a, i) { return iterable[i - 1] !== a }));
}
console.log(uniqueInOrder("aaaaaBBBDSJJJJ"))
@daymos Callback is invoked with three arguments. See here.
版权声明:本文标题:javascript - js Array.prototype.filter.call() - can someone explain me how this piece of code works? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741910878a2404435.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论