skip to Main Content

I have two arrays

first= [1,1,1,1,1,2,2,2,2]

second =[1,1,1,1,1]

The javascript function should return True only when all elements in second array is present in first array and if second =[1,1,1,1] or [1,1,1],[1,1],[1],[] it should return false.

Thanks in advance! Cheers

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

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

3

Answers


  1. First conditional expression should be checking length

        if(first.length != second.length) {
           //They don't have the same number of element thus we don't need to check further
            return -1
          }

    Then, try re-arranging the array in order.
    using an ordering algorithm

    Then with two loop check if each element of the same index matches each array like below

        for(int i =0;i<length;i++)
    {
      if(first[i] != second[i]) {
    
    //if they don't at this instance both array doesnot have all elements
    return -1;
      }
    }

    Hope this helps

    Login or Signup to reply.
  2. 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) {
      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 (!counts1st[count] || counts2nd[count] !== counts1st[count]) return false;
      }
      return true;
    }
    Login or Signup to reply.
  3. simple JS-magic, (if I understand the problem):

    String(first).includes(second) && // second in first
    /[^1,]/.test(second) // not all 1s or empty
    

    Sometimes dynamic types really simplify things by treating data generically; use that strength where you can.

    If the second array is not allowed to be uniform elements, but could be all non-1 digits, then it’s more complicated:

    String(first).includes(second) && // second in first
    RegExp(`[^${second[0]},]`).test(second) // not all uniform or empty
    

    as a function:

    function allElementsPresent(first, second) {  
      return String(first).includes(second) && /[^1,]/.test(second)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search