Javascript Array where(predicate)

Description

Javascript Array where(predicate)


'use strict';/*from  www .  j a v a  2s  . c  om*/
Array.prototype.where = function (predicate) {
    let filteredArray = [];
    for (let element of this) {
        if (predicate(element)) {
            filteredArray.push(element);
        }
    }

    return filteredArray;
};

Array.prototype.removeItem = function (item) {
    return this.where(e => e !== item);
};

let arr = [1,2,3,4,5,1,2,3,1,1,1,1];
console.log(arr.removeItem(2));

Javascript Array where(predicate)

// predicate is a method that accepts one parameter and returns a boolean.
Array.prototype.where = function(predicate) {
    var derivedArray = [];
    for (i = 0; i < this.length; i += 1) {
        if (predicate(this[i])) {
            derivedArray.push(this[i]);// w  ww .  ja  v  a 2 s. c  o m
        }
    }
    return derivedArray;
}

Javascript Array where(predicate)

Array.prototype.where = function (predicate) {
    if (predicate == null || typeof (predicate) !== 'function') throw new Error('predicate should');
    var result = [];
    for (var i = 0; i < this.length; i++) {
        if (predicate(this[i], i)) result.push(this[i]);
    }//from   w w  w.ja  va  2  s .com
    return result;
};

Array.prototype.select = function (selector) {
    if (selector == null || typeof (selector) !== 'function') throw new Error('selector should');
    var result = [];
    for (var i = 0; i < this.length; i++) {
        result.push(selector(this[i]));
    }
    return result;
};

Javascript Array where(predicate)

Array.prototype.where = function (predicate) {
    var ret = [];
    for (var i = 0; i < this.length; ++i) {
        if (predicate(this[i], i))
            ret.push(this[i]);/*from www .  j  a v a 2  s  . c o  m*/
    }
    return ret;
};



PreviousNext

Related