Javascript Array isSubsetOf(parentArray)

Description

Javascript Array isSubsetOf(parentArray)


//Make an array method that can return whether or not a context array is a subset
//of an input array. To simplify the problem, you can assume that both arrays will
//contain only strings.

Array.prototype.isSubsetOf = function(parentArray) {
  for(var i = 0; i < this.length; i++) {
    if(parentArray.indexOf(this[i]) === -1) {
      return false;
    }/*  www. ja  va  2s  .  c  o  m*/
  }
 return true;
};

Javascript Array isSubsetOf(parentArray)

Array.prototype.isSubsetOf = function(parentArray) {
  //store the parent array values as keys in object
  storageObj = {};/* ww w.j a v  a  2 s .co m*/

  //loop through the parent array and add values as keys
  for (let i = 0; i < parentArray.length; i++) {
    storageObj[parentArray[i]] = true;
  };

  //loop through (this) array and see if all values are found in storage
  for (let i = 0; i < this.length; i++) {
    if(!storageObj[this[i]]) {
      return false;
    }
  }
  
  return true;
};



PreviousNext

Related