Filter Non-Unique Array Values

JavaScriptJavaScriptBeginner
Practice Now

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

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.


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-28297{{"`Filter Non-Unique Array Values`"}} javascript/data_types -.-> lab-28297{{"`Filter Non-Unique Array Values`"}} javascript/arith_ops -.-> lab-28297{{"`Filter Non-Unique Array Values`"}} javascript/comp_ops -.-> lab-28297{{"`Filter Non-Unique Array Values`"}} javascript/higher_funcs -.-> lab-28297{{"`Filter Non-Unique Array Values`"}} javascript/spread_rest -.-> lab-28297{{"`Filter Non-Unique Array Values`"}} end

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:

  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 the original array.
  3. 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.

Other JavaScript Tutorials you may like