Filtering in javascript
By Anatoly Mironov
The simplest and the best way to filter an array is to extend the Array.prototype as described here:
if (!Array.prototype.filter) {
Array.prototype.filter = function (func) {
var len = this.length;
if (typeof func != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments\[1\];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this\[i\];
if (func.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
```Then let's filter on [titles](/2011/11/21/sorting-dates-in-javascript/ "See an example for Sorting with Titles"), which [start with](http://stackoverflow.com/questions/646628/javascript-startswith "See the solution for startsWith in javascript on Stackoverflow") "N":
function startsWithN(element, index, array) { return element.toLowerCase().indexOf(“n”) == 0; }
var filtered = dates.filter(startsWithN);
$("#contactContainer").empty(); $("#contactTemplate").tmpl(filtered).appendTo("#contactContainer");