Introduction
In this lab, we will be exploring how to filter out non-unique values from an array using JavaScript. We will learn how to use the Set constructor and the spread operator to create an array of unique values, and then use the Array.prototype.filter() method to filter out the non-unique values. This lab will help us understand how to manipulate arrays in JavaScript and improve our problem-solving skills.
How to Filter Non-Unique Values in an Array in JavaScript
To filter non-unique values in an array in JavaScript, you can create a new array with only the unique values. Here's how:
- 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 the original array. - Use
Array.prototype.filter()to create an array containing only the unique values.
Here's an example function that does this:
const filterNonUnique = (arr) =>
[...new Set(arr)].filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
You can use this function with any array to filter out the non-unique values. For example:
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]
Summary
Congratulations! You have completed the Filter Non-Unique Array Values lab. You can practice more labs in LabEx to improve your skills.