Filter an Array using JavaScript

Let’s see how to filter element values in an Array using JavaScript. We will use the JavaScript Array.Filter() to do so. Here’s the code to filter out all Even numbers from an array

Note: The filter() method is a new method added to the Array object with JavaScript 1.6 onwards (ECMAScript 5). It is not supported by all browsers like IE8. Hence we will first use if (!Array.prototype.filter) to check if the filter method is implemented in your browser, else provide an implementation for the filter() method, so that it works on most browsers like IE8.

Here’s the filter() method as provided by Mozilla

if (!Array.prototype.filter) {
Array.prototype.filter = function (fun /*, thisp */) {
"use strict";

if (this === void 0 this === null)
throw new TypeError();

var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();

var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}

return res;
};
}

Once you have declared the filter() method, use it in your page as shown below to filter out even numbers in the array:

javascript filter array

OUTPUT

image

See a Live Demo

If you are dealing with a JSON object, check my post Filter and Convert JSON Object to a String






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

JavaScript Virtual Keyboard said...

very cool & good array method, I had to work with JS array alot but I just used other lib to process them


thank you very much for sharing.

Test said...
This comment has been removed by the author.
Test said...

You might be interested in this github project that provides a shim for the new ES5 functionality for browsers that don't support it...

https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js

Suprotim Agarwal said...

Thanks for sharing this library Elijah!