isSubset of two arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two arrays of literals. The function should determine whether or not the second array is a subset of the first array, keeping these things in mind −

  • All values of array1 should be defined in array2

  • If duplicate values exist in array1, they should also take into account in array2.

For example, if arr1 = ["a", "a"] and arr2 = ["b", "a"] then isSubset is false because "a" appears twice in the first but only once in the second.


The code for this will be −

const isSubset = (arr1, arr2) => {
   const count = (arr, ind) => {
      let i = arr.length;
      while (i−−) hash[arr[i]] = (hash[arr[i]] || 0) + ind;
   const hash = {};
   let i, keys;
   count(arr1, 1);
   count(arr2, −1);
   keys = Object.keys(hash);
   i = keys.length;
   while (i−−) {
      if (hash[keys[i]]){
         return false;
   return true;
console.log(isSubset(["B", "A", "C", "A"], ["A", "B", "C", "A"]));
console.log(isSubset(["B", "A", "C", "A"], ["A", "B", "C", "D"]));


And the output in the console will be −

Published on 25-Nov-2020 16:20:57