Check if arrays have same contents

JavaScript, Array · Oct 19, 2020

Checks if two arrays contain the same elements regardless of order.

  • Use a for...of loop over a Set created from the values of both arrays.
  • Use Array.prototype.filter() to compare the amount of occurrences of each distinct value in both arrays.
  • Return false if the counts do not match for any element, true otherwise.
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;
haveSameContents([1, 2, 4], [2, 4, 1]); // true

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Comparison

    Comparing values in JavaScript is one of the most common tasks, yet it has a lot of things you should bear in mind.

    Collection · 11 snippets

  • Array is contained in other array

    Checks if the elements of the first array are contained in the second one regardless of order.

    JavaScript, Array · Oct 22, 2020

  • Check if two arrays intersect

    Determines if two arrays have a common item.

    JavaScript, Array · Feb 17, 2023

  • Mapped array symmetric difference

    Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.

    JavaScript, Array · Oct 22, 2020