Mapped Array Difference

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the implementation of the differenceBy function in JavaScript. This function allows us to find the difference between two arrays by applying a provided function to each element in both arrays. We will learn how to use Set, Array.prototype.map(), and Array.prototype.filter() to effectively compare and filter arrays based on a specific criterion.


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/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28484{{"`Mapped Array Difference`"}} javascript/data_types -.-> lab-28484{{"`Mapped Array Difference`"}} javascript/arith_ops -.-> lab-28484{{"`Mapped Array Difference`"}} javascript/comp_ops -.-> lab-28484{{"`Mapped Array Difference`"}} javascript/higher_funcs -.-> lab-28484{{"`Mapped Array Difference`"}} javascript/destr_assign -.-> lab-28484{{"`Mapped Array Difference`"}} end

Function to Return the Difference of Two Arrays by Mapping

To get started with coding, open your Terminal/SSH and type node.

This function takes two arrays and applies the provided function to each element in both arrays to return their difference.

To do this:

  • Create a Set by applying the function (fn) to each element in the second array (b).
  • Use Array.prototype.map() to apply the function (fn) to each element in the first array (a).
  • Use Array.prototype.filter() in combination with the function (fn) on the first array (a) to only keep values not contained in the second array (b), using Set.prototype.has().

Here's the code for the function:

const differenceBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.map(fn).filter((el) => !s.has(el));
};

Here are some examples of how to use the function:

differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], (v) => v.x); // [2]

Summary

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

Other JavaScript Tutorials you may like