Can anybody explain how exactly Filter and IndexOf

2020-05-05 01:09发布

I have the following function, which pretty much does what it supposed to, but I would like to understand exactly what it does on each steps of its loop.

Could you please take a look to the function below and give me a clear explanation commenting each step or the Filter and IndexOf methods?

Thank you very much in advance.

var arr = [6,2,6,8,9,9,9,4,5];

var unique = function(){
  return arr.filter(function(e, i, a) {
      return i === a.indexOf(e);
  })
}

unique();

标签: javascript
2条回答
男人必须洒脱
2楼-- · 2020-05-05 01:46

indexOf returns the first index of an element in an array:

[1,2,2,3].indexOf(2); // 1

So if you use filter as in your example when it gets to the second occurance of an element the index (i in your example) will not be equal to the value returned by indexOf and be dropped. In my array above the second 2 is at position 2 which obviously doesn't strictly equal the one returned by indexOf.

[1,2,2,3].filter((value, index, array) => array.indexOf(value) === index);
// first iteration: value is 1, index is 0, indexOf is 0 0===0 keep 1
// second: value is 2, index is 1, indexOf is 1, 1===1 keep 2
// third: value is 2, index is 2, indexOf is 1, 1===2 false! toss 2
// etc. 

The end effect is that any duplicate elements get dropped from the copy returned by filter. And it is a copy, the original array is not mutated.

EDIT

I should probably mention that recent versions of JavaScript give us a better way:

let arrayWithDupes = [1,2,2,3];
let uniq = Array.from(new Set(arrayWithDupes)); // [1,2,3]
查看更多
Summer. ? 凉城
3楼-- · 2020-05-05 01:46

If log the values like:

var arr = [6,2,6,8,9,9,9,4,5];
var unique = function(){
  return arr.filter(function(e, i, a) {
      console.log('e: ' + e);
      console.log('i: ' + i);
      console.log('a: ' + a);
      return i === a.indexOf(e);
  })
}

var unq = unique();

console.log(unq);

you will get:

"e: 6"
"i: 0"
"a: 6,2,6,8,9,9,9,4,5"

and so on...

e = current element from array, i = index of the array, a = array source;

Filer function: "The filter() method creates an array filled with all array elements that pass a test (provided as a function)."

indexOf: "The indexOf() method searches the array for the specified item, and returns its position."

查看更多
登录 后发表回答