Filter Unique Array Values

Beginner

This tutorial is from open-source community. Access the source code

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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

How to Filter Unique Values in an Array using JavaScript

To filter unique values in an array using JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the Set constructor and the spread operator (...) to create an array of the unique values in your original array.
  3. Use Array.prototype.filter() to create an array containing only the non-unique values.
  4. Define a function called filterUnique that takes in an array as an argument and applies the above steps to it.
  5. Call the filterUnique function 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.