Filter Unique Array Values

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28299{{"`Filter Unique Array Values`"}} javascript/data_types -.-> lab-28299{{"`Filter Unique Array Values`"}} javascript/arith_ops -.-> lab-28299{{"`Filter Unique Array Values`"}} javascript/comp_ops -.-> lab-28299{{"`Filter Unique Array Values`"}} javascript/higher_funcs -.-> lab-28299{{"`Filter Unique Array Values`"}} javascript/spread_rest -.-> lab-28299{{"`Filter Unique Array Values`"}} end

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.

Other JavaScript Tutorials you may like