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:
OUTPUT
See a Live Demo
If you are dealing with a JSON object, check my post Filter and Convert JSON Object to a String
Tweet
4 comments:
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.
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
Thanks for sharing this library Elijah!
Post a Comment