Unique Array Difference Calculation

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to calculate the difference between two arrays without filtering duplicate values. The lab will guide you through the process of creating a Set from one array to get the unique values, and then using Array.prototype.filter() on the other array to keep only values that are not contained in the Set. By the end of the lab, you will have a better understanding of how to work with arrays 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`") subgraph Lab Skills javascript/variables -.-> lab-28139{{"`Unique Array Difference Calculation`"}} javascript/data_types -.-> lab-28139{{"`Unique Array Difference Calculation`"}} javascript/arith_ops -.-> lab-28139{{"`Unique Array Difference Calculation`"}} javascript/comp_ops -.-> lab-28139{{"`Unique Array Difference Calculation`"}} javascript/higher_funcs -.-> lab-28139{{"`Unique Array Difference Calculation`"}} end

Array Difference

To find the difference between two arrays, follow these steps:

  1. Open the Terminal/SSH and type node to start coding.

  2. Create a Set from array b to extract the unique values from b.

  3. Use Array.prototype.filter() on array a to keep only the values that are not in array b, using Set.prototype.has().

Here is the code:

const difference = (a, b) => {
  const s = new Set(b);
  return a.filter((x) => !s.has(x));
};

Example usage:

difference([1, 2, 3, 3], [1, 2, 4]); // Output: [3, 3]

Summary

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

Other JavaScript Tutorials you may like