Javascript Array Prototype all()

Introduction

all() returns true only if the predicate supplied returns true for all the items in the array

[1, 2, 3].all(isGreaterThanZero) => true
[-1, 0, 2].all(isGreaterThanZero) => false
Array.prototype.all = function (p) {
  for(let i = 0, j = this.length; i < j; i++) {
    if(!p(this[i])) return false;
  }//from w w  w. j a  va  2  s . c om

  return true;
};


function isGreaterThanZero(num) {
  return num > 0;
}

function isLessThanZero(num) {
  return num < 0;
}

console.log([1, 2, 3].all(isGreaterThanZero));
console.log([-1, 2, -3].all(isGreaterThanZero));



PreviousNext

Related