Javascript Array isSubsetOf()

Description

Javascript Array isSubsetOf()



Array.prototype.isSubsetOf = function() {
    var args=arguments[0];
    var len=this.length;
    var i;/*www .  ja  v a  2 s  .c  o  m*/
    var counter=0;
    console.log(args);
    for(i=0; i<len; i++){
        if(args.indexOf(this[i])>=0){
            counter++;
        }
    }
    if(counter===len){
        return true;
    }
    return false;
};

Javascript Array isSubsetOf()

Array.prototype.isSubsetOf = function() {
  var args = arguments[0];

  for (var i = 0; i < this.length; i++) {
    if (args.indexOf(this[i]) < 0) {
      return false;
    }//from  w w  w  .  j  a  va2 s.  c om
  }
  return true;
};
  // var args = Array.prototype.slice.call(arguments);

  // Get arguments
  // Iterate through "this" array.  Check for indexes from args array
  // If any return -1, then return false
  // IF all return >=0, then return true
var arr1 = ['cat', 'dog', 'pig', 'bat'];
var arr2 = ['pig', 'dog'];
var arr3 = ['tree', 'pig'];

var result = arr3.isSubsetOf(arr1);

console.log(result);

Javascript Array isSubsetOf()

//Determine whether or not a context array is a subset of an input array

Array.prototype.isSubsetOf = function() {
  //subsArr gives access to context array
  //argsArr gives access to input array
  //simply loop over context and find out if values are within input
  //if not, we must return false since all of context array 
  //must be part of input array
  var subsArr = this; argsArr = arguments[0]; bool = true;
    subsArr.forEach(function(el){
      if(argsArr.indexOf(el) === -1){
        bool = false;//from  ww w.jav  a  2s.c om
      } 
    });
    return bool;
};

  //ex
  var result = ['cat', 'dog', 'cow'].isSubsetOf(['dog', 'cow', 'fox', 'cat']);//true



PreviousNext

Related