Array Symmetric Difference Based on Function

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to find the symmetric difference between two arrays based on a provided function using JavaScript. We will use the Array.prototype.filter() and Array.prototype.findIndex() methods to compare the elements of the two arrays and return the values that are unique to each array. By the end of this lab, you will have a better understanding of how to use these methods to compare and manipulate 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`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28333{{"`Array Symmetric Difference Based on Function`"}} javascript/data_types -.-> lab-28333{{"`Array Symmetric Difference Based on Function`"}} javascript/arith_ops -.-> lab-28333{{"`Array Symmetric Difference Based on Function`"}} javascript/comp_ops -.-> lab-28333{{"`Array Symmetric Difference Based on Function`"}} javascript/higher_funcs -.-> lab-28333{{"`Array Symmetric Difference Based on Function`"}} javascript/spread_rest -.-> lab-28333{{"`Array Symmetric Difference Based on Function`"}} end

A Function to Find Array Symmetric Difference

To find symmetric difference between two arrays using a provided function as a comparator, follow these steps:

  1. Open Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.filter() and Array.prototype.findIndex() methods to find the appropriate values.
  3. Use the given code to perform the operation.
const symmetricDifferenceWith = (arr, val, comp) => [
  ...arr.filter((a) => val.findIndex((b) => comp(a, b)) === -1),
  ...val.filter((a) => arr.findIndex((b) => comp(a, b)) === -1)
];

For example, consider the following input:

symmetricDifferenceWith(
  [1, 1.2, 1.5, 3, 0],
  [1.9, 3, 0, 3.9],
  (a, b) => Math.round(a) === Math.round(b)
); // [1, 1.2, 3.9]

The above code will return [1, 1.2, 3.9] as the symmetric difference between the two arrays.

Summary

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

Other JavaScript Tutorials you may like