Array Symmetric Difference

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring the concept of finding the symmetric difference between two arrays in JavaScript. This lab will guide you through the process of creating a Set from each array to get the unique values and using the filter() method to only keep values not contained in the other. By the end of this lab, you will have a solid understanding of how to implement this logic and be able to apply it to your own projects.


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

Array Symmetric Difference

To find the symmetric difference between two arrays and include duplicate values, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Create a Set from each array to get the unique values of each one.
  3. Use Array.prototype.filter() on each of them to only keep values not contained in the other.

Here's the code:

const symmetricDifference = (a, b) => {
  const sA = new Set(a),
    sB = new Set(b);
  return [...a.filter((x) => !sB.has(x)), ...b.filter((x) => !sA.has(x))];
};

You can use the following examples to test the function:

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

Summary

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

Other JavaScript Tutorials you may like