Add where method to Array - Node.js Array

Node.js examples for Array:Add Element

Description

Add where method to Array

Demo Code

Array.prototype.where = function (inclusionTest) {
    var results = [];
    for (var i = 0; i < this.length; i++) {
        if (inclusionTest(this[i]))
            results.push(this[i]);/*from ww w  .  j ava 2  s.  c  o m*/
    }
    return results;
};

Array.prototype.select = function (projection) {
    var results = [];
    for (var i = 0; i < this.length; i++) {
        results.push(projection(this[i]));
    }
    return results;
};

var children = [{ id: 1, Name: "Rob" }, { id: 2, Name: "Sansa" }, { id: 3, Name: "Arya" }, { id: 4, Name: "Brandon" }, { id: 5, Name: "Rickon" }];
var filteredChildren = children.where(function (x) {
    return x.id % 2 == 0;
}).select(function (x) {
    return x.Name;
});
console.dir(children);
console.dir(filteredChildren);

Related Tutorials