JavaScript: implementing the grep() function

JavaScript: implementing the grep() function

A simple JavaScript implementation of the grep() utility function for arrays and DOM elements.

The grep() utility is very popular among jQuery developers. Its main purpose is to filter an array (or array-like) object and return a filtered array containing only the items that satisfy a certain condition. In this article I'm going to show you how to implement something similar in pure JavaScript.

grep() accepts two basic parameters, namely the array we want to filter and a callback function. The callback function works on each array's item and returns a boolean value, meaning that the filtering condition has been met.

Here's our function:

var grep = function(items, callback) {
    var filtered = [],
        len = items.length,
        i = 0;
    for (i; i < len; i++) {
        var item = items[i];
        var cond = callback(item);
        if (cond) {
            filtered.push(item);
        }
    }

    return filtered;
};

For example, given the following HTML structure:

<ul id="test">
	<li>A</li>
	<li>B</li>
	<li>2</li>
	<li>3</li>
	<li>C</li>
</ul>​

We want to select only the list items which contains letters. Here's how we can do:

var elements = document.getElementsByTagName('li');

var set = grep(elements, function(node) {
    var txt = node.firstChild.nodeValue;
    return /^[a-z]+$/i.test(txt);
});

var result = '';

for (var i = 0; i < set.length; i++) {
    result += set[i].firstChild.nodeValue + ' ';
}


alert(result); // A B C

You can see the demo below.

Demo

Live demo