Computer Magic Logo
Filter array

Thursday, February 11, 2016

Published by Aristotelis Pitaridis

The grep member function finds the elements of an array which satisfy one or more criteria and returns them as a new array. The original array is not affected.

$(function () {
    var Products = [{
        Name: "Turbo X45",
        Type: "Mouse",
        Price: 12.99
    },
    {
        Name: "Fast F56",
        Type: "Mouse",
        Price: 15.99
    },
    {
        Name: "Natural 56",
        Type: "Keyboard",
        Price: 21.99
    },
    {
        Name: "Super 45",
        Type: "Mouse",
        Price: 17.99
    }];

    var FilteredProducts = $.grep(Products, function (CurrentElement, Index) {
        return CurrentElement.Type === "Mouse" && CurrentElement.Price<17;
    }, true);

    console.log(FilteredProducts);
});

The grep member function has a temporary third parameter. This parameter's default value is false which means that the member function will return all the objects which meet the criteria. If we define the true value, the member function will return all the objects which does not meet the criteria.