Select Objects in Array Based on Regex Match

前端 未结 2 749
粉色の甜心
粉色の甜心 2021-01-11 23:11

How can I return only the objects in an array that meet a certain criteria using javascript?

For instance, if I have [\'apple\',\'avocado\',\'banana\',\'cherry\'] an

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-11 23:42

    If targeting ES3 (the version of javascript that is most common, and safe to use) then use

    var arr  = ['apple','avocado','banana','cherry'];
    
    var filtered = (function(){
        var filtered = [], i = arr.length;
        while (i--) {
            if (/^A/.test(arr[i])) {
                filtered.push(arr[i]);
            }
        }
        return filtered;
    })();
    alert(filtered.join());
    

    But if you are targeting ES5 then you can do it using

    var filtered = arr.filter(function(item){
        return /^A/.test(item);
    });
    alert(filtered.join());
    

    If you want to you can include the ES5 filter method in ES3 by using

    if (!Array.prototype.filter) {
        Array.prototype.filter = function(fun /*, thisp*/){
            var len = this.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 this) {
                    var val = this[i]; // in case fun mutates this
                    if (fun.call(thisp, val, i, this)) 
                        res.push(val);
                }
            }
    
            return res;
        };
    }
    

    See https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/filter#Compatibility for more.

    UPDATE Answer for the updated question

    var filtered = (function(pattern){
        var filtered = [], i = arr.length, re = new RegExp('^' + pattern);
        while (i--) {
            if (re.test(arr[i])) {
                filtered.push(arr[i]);
            }
        }
        return filtered;
    })('A'); // A is the pattern
    
    alert(filtered.join());
    

提交回复
热议问题