Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Because the map method returns an array, you can call another array method directly after it. The same is true for the filter method. This is commonly called chaining methods, because each call is like a link in a chain.
Snippets from the Video
const arr = [1,2,3];
const smallerArr = arr.filter(number => number !== 2);
const incrementedArr = smallerArr.map(number => number + 1);
console.log(incrementedArr); // => [2,4]
Removing Duplicates from an Array
To remove duplicate elements from an array, we can use filter(). Remember, the filter method provides three parameters to our callback function: the current element being processed in the array, the index of the current element being processed in the array, and the array filter() was called upon.
We can compare the index of the current element to the index of the current element in the array that filter() was called upon to determine if we've already encountered that element value. This works because the indexOf method will return the index of the first occurrence that is found in the array. So, indexes of duplicate elements will not equal the index of the first occurrence of their values.
const numbers = [1, 1, 2, 3, 4, 3, 5, 5, 6, 7, 3, 8, 9, 10];
const unique = numbers.filter(function(number, index, array) {
return index === array.indexOf(number);
});
console.log(unique); // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up