javascriptarraysloops

Count exact occurrences of a certain number in array and return either True or False


I have two arrays

Array1 = [1,1,1,2,2,2,3,3] 
Array2 =[1,1,2,1]

Comparing both of the arrays should return result as True as there are same number of occurrences of Integer 1.


Array2 = [1,1,2]  //Should return False. 

In the above case, the result should be false as the no. Of occurrences of 1 or 2 in Array2 don't match with the no. Of occurrences of 1 and 2 in Array1.

Array2 = [1,1,2,3,1] //should return True.

I tried this but doesn't work for other instances.

function allElementsPresent(first, second) {
  return second.every((element) => first.includes(element));
}

Thanks in advance! Cheers


Solution

  • I believe I understand what you want to accomplish. You want to see if the number of occurrences in the second array matches the first. If that's the case, I've used this answer as a basis

    function allElementsPresent(first, second, matchAll = false) {
      if (first.length > 0 && second.length === 0) return false;
      var counts1st = {};
      var counts2nd = {};
    
      for (var num of first) {
        counts1st[num] = counts1st[num] ? counts1st[num] + 1 : 1;
      }
      for (var num of second) {
        counts2nd[num] = counts2nd[num] ? counts2nd[num] + 1 : 1;
      }
    
      for (var count in counts2nd) {
        if (matchAll && (!counts1st[count] || counts1st[count] !== counts2nd[count])) return false;
        if (!matchAll && (counts1st[count] && counts1st[count] === counts2nd[count])) return true;
      }
      return matchAll ? true : false;
    }