Javascript Array Prototype any()

Introduction

This function returns true if at least one of the items in the array returns true for the predicate supplied

[-1, 2, 3].any(isGreaterThanZero) => true
[-1, -2, -3].any(isGreaterThanZero) => false

Array.prototype.any = function (p) {
  for(let i = 0, j = this.length; i < j; i++) {
    if(p(this[i])) return true;
  }/*from ww  w. j av  a2  s .c o m*/

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

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

console.log([-1, 2, 3].any(isGreaterThanZero));  // => true
console.log([-1, -2, -3].any(isGreaterThanZero)); // => false



PreviousNext

Related