Check if Arrays Have Same Contents

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to check if two arrays have the same contents in JavaScript. We will create a function that takes in two arrays and returns true if they contain the same elements, regardless of order, and false otherwise. We will use a combination of Set, for...of loop, and Array.prototype.filter() to achieve this functionality.


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/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28164{{"`Check if Arrays Have Same Contents`"}} javascript/data_types -.-> lab-28164{{"`Check if Arrays Have Same Contents`"}} javascript/arith_ops -.-> lab-28164{{"`Check if Arrays Have Same Contents`"}} javascript/comp_ops -.-> lab-28164{{"`Check if Arrays Have Same Contents`"}} javascript/cond_stmts -.-> lab-28164{{"`Check if Arrays Have Same Contents`"}} javascript/loops -.-> lab-28164{{"`Check if Arrays Have Same Contents`"}} javascript/higher_funcs -.-> lab-28164{{"`Check if Arrays Have Same Contents`"}} javascript/spread_rest -.-> lab-28164{{"`Check if Arrays Have Same Contents`"}} end

Checking for Same Contents in Arrays

To check if two arrays contain the same elements regardless of order, follow these steps:

  1. Open the Terminal/SSH and type node.
  2. Use a for...of loop over a Set created from the values of both arrays.
  3. Use Array.prototype.filter() to compare the amount of occurrences of each distinct value in both arrays.
  4. Return false if the counts do not match for any element, true otherwise.

Here's the code for the same:

const haveSameContents = (a, b) => {
  for (const v of new Set([...a, ...b]))
    if (a.filter((e) => e === v).length !== b.filter((e) => e === v).length)
      return false;
  return true;
};

To test the function, use the following code:

haveSameContents([1, 2, 4], [2, 4, 1]); // true

Summary

Congratulations! You have completed the Check if Arrays Have Same Contents lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like