Introduction
In this lab, we will explore the concept of filtering out unique values from an array in JavaScript. We will use the Set constructor and the spread operator to create an array of unique values and then filter out only the non-unique values using the filter() method. This lab will help you understand the importance of filtering unique values in an array and how it can be achieved using simple JavaScript code.
How to Filter Unique Values in an Array using JavaScript
To filter unique values in an array using JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
Setconstructor and the spread operator (...) to create an array of the unique values in your original array. - Use
Array.prototype.filter()to create an array containing only the non-unique values. - Define a function called
filterUniquethat takes in an array as an argument and applies the above steps to it. - Call the
filterUniquefunction with your array as the argument.
Here is an example code snippet to achieve this:
const filterUnique = (arr) =>
[...new Set(arr)].filter((i) => arr.indexOf(i) !== arr.lastIndexOf(i));
filterUnique([1, 2, 2, 3, 4, 4, 5]); // [2, 4]
In the above code snippet, the filterUnique function takes in an array and applies the Set constructor and Array.prototype.filter() method to it to return an array with only the non-unique values.
Summary
Congratulations! You have completed the Filter Unique Array Values lab. You can practice more labs in LabEx to improve your skills.