Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialnfs
35,526 PointsHow 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
231,268 PointsThe 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.
Samuel Cleophas
12,348 PointsSamuel Cleophas
12,348 PointsThat's bloody amazing.