Array Unique Symmetric Difference

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of finding unique symmetric difference between two arrays in JavaScript. We will use the Array.prototype.filter() and Array.prototype.includes() methods to remove duplicate values from each array and then create a Set from the results to obtain the final output. This exercise will help to improve your understanding of array manipulation and Set data structure in JavaScript.


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-28162{{"`Array Unique Symmetric Difference`"}} javascript/data_types -.-> lab-28162{{"`Array Unique Symmetric Difference`"}} javascript/arith_ops -.-> lab-28162{{"`Array Unique Symmetric Difference`"}} javascript/comp_ops -.-> lab-28162{{"`Array Unique Symmetric Difference`"}} javascript/higher_funcs -.-> lab-28162{{"`Array Unique Symmetric Difference`"}} javascript/spread_rest -.-> lab-28162{{"`Array Unique Symmetric Difference`"}} end

Array Unique Symmetric Difference Function

To practice coding, open the Terminal/SSH and type node. The following function returns the unique symmetric difference between two arrays. It removes duplicate values from either array.

To achieve this, use Array.prototype.filter() and Array.prototype.includes() on each array to remove values contained in the other. Create a Set from the results to remove duplicate values.

const uniqueSymmetricDifference = (a, b) => [
  ...new Set([
    ...a.filter((v) => !b.includes(v)),
    ...b.filter((v) => !a.includes(v))
  ])
];

Use the function as shown below:

uniqueSymmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
uniqueSymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 3]

Summary

Congratulations! You have completed the Array Unique Symmetric Difference lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like