Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Array Iteration Methods Combining Array Methods Chaining Array Methods

How does this work? Can I get an explanation?

In the teacher's notes:

const numbers = [1, 1, 2, 3, 4, 3, 5, 5, 6, 7, 3, 8, 9, 10];

const unique = numbers.filter( (number, index, array) => { 
  return index === array.indexOf(number); 
});

console.log(unique);

Umm... I don't get it. This one really puzzled me.

1 Answer

Steven Parker
Steven Parker
218,569 Points

The indexOf method returns the index number of the first item that matches, so if the current index is equal to "indexOf", then this item must be the first of it's value in the array. The filter expression is true, so the item is included in the output array.

But if a second (or third, fourth, etc) item of the same value is encountered, the index value will not match, so the filter expression is false and the item is not included.

So in short, the filter expression is eliminating any duplicates.