JSFiddle - React, Tailwind, and code Playground

by devcurry_com

HTML

<title>Filter an array using JavaScript by DevCurry.com</title>

JavaScript

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;
            };
        }

        function isEven(element, index, array) {
            return ((element % 2 == 0));
        }

        var arr = new Array(1, 5, 6, 7, 9, 11, 14, 16, 20);
        var newArr = arr.filter(isEven);
        document.writeln("Here's a list of all Even Numbers: " + newArr);