Javascript Array filter(callback)

Description

Javascript Array filter(callback)


Array.prototype.filter = function(callback){
    const newArr = []//from   www . j  a  v  a  2  s  .c o  m
    for(let i = 0; i < this.length; i += 1){
        if(callback(this[i])){
            newArr.push(this[i])
        }
    }
    return newArr
}

const arr = [1,2,3,4,5,6,7]
const newArr = arr.filter((value) => {
    return (value%2 === 0)
})
console.log(newArr)

Javascript Array filter(callback)

Array.prototype.filter = function(callback) {
    const newArray = [];//w  w w  .java 2 s  .c o m

    for (let i = 0; i < this.length; i += 1){
        if (callback(this[i])) {
            newArray.push(this[i]);
        }
    }
    
    return newArray;
}

Javascript Array filter(callback)

// Array.prototype.filter
Array.prototype.filter = function filter(callback) {
 if (typeof callback !== 'function') {
  throw new TypeError(callback + ' is not a function');
 }

 for (var array = this, result = [], index = 0, length = array.length; index < length; ++index) {
  if (index in array && callback.call(arguments[1], array[index], index, array)) {
   result.push(array[index]);// w  w  w  .j a v  a2  s. c  om
  }
 }

 return result;
};

Javascript Array filter(callback)

Array.prototype.filter = function(callback){
 var a = -1,//from   ww  w  .j av  a 2  s .co  m
  len = this.length,
  result = [];
 while(++a < len){
  callback(this[a], a, this) && result.push(this[a]);
 }
 return result;
};

Javascript Array filter(callback)

Array.prototype.filter = function filter(callback) {
 if (this === undefined || this === null) {
  throw new TypeError(this + ' is not an object');
 }

 if (typeof callback !== 'function') {
  throw new TypeError(callback + ' is not a function');
 }

 var/*from  w w  w  . j  av  a 2 s  .  c  om*/
 object = Object(this),
 scope = arguments[1],
 arraylike = object instanceof String ? object.split('') : object,
 length = Math.max(Math.min(arraylike.length, 9007199254740991), 0) || 0,
 index = -1,
 result = [],
 element;

 while (++index < length) {
  element = arraylike[index];

  if (index in arraylike && callback.call(scope, element, index, object)) {
   result.push(element);
  }
 }

 return result;
};



PreviousNext

Related