Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js Array.prototype.filter.call() - can someone explain me how this piece of code works?

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"))
like image 668
daymos Avatar asked Oct 03 '15 12:10

daymos


1 Answers

Let'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"))
like image 51
Saar Avatar answered Oct 23 '22 05:10

Saar