最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select Objects in Array Based on Regex Match - Stack Overflow

programmeradmin2浏览0评论

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'] and want to only output fruit that begin with the letter 'A'.

EDIT:

Took Sean Kinsey's function below and tried to make it more flexible by passing in the array and letter to match:

function filterABC(arr,abc) {

var arr = arr;

var filtered = (function(){
    var filtered = [], i = arr.length;
while (i--) {
    if ('/^' + abc + '/'.test(arr[i])) {
    filtered.push(arr[i]);
    }
}
return filtered;
})();

return filtered.join(); 

}

Trying to call it with filterABC(arr,'A') or filterABC(arr,'A|B|C|') to output all matches from A to C but having trouble with this part.

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'] and want to only output fruit that begin with the letter 'A'.

EDIT:

Took Sean Kinsey's function below and tried to make it more flexible by passing in the array and letter to match:

function filterABC(arr,abc) {

var arr = arr;

var filtered = (function(){
    var filtered = [], i = arr.length;
while (i--) {
    if ('/^' + abc + '/'.test(arr[i])) {
    filtered.push(arr[i]);
    }
}
return filtered;
})();

return filtered.join(); 

}

Trying to call it with filterABC(arr,'A') or filterABC(arr,'A|B|C|') to output all matches from A to C but having trouble with this part.

Share Improve this question edited May 17, 2010 at 20:55 Choy asked May 17, 2010 at 19:41 ChoyChoy 2,11711 gold badges39 silver badges49 bronze badges 2
  • Do you really mean objects in an array, or do you just mean strings in an array? – Mark Byers Commented May 17, 2010 at 19:44
  • Did my updated answer solve your problem? – Sean Kinsey Commented May 18, 2010 at 5:37
Add a comment  | 

2 Answers 2

Reset to default 15

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());

Your problem is with generating your regex on the fly. You cannot make a valid regex by concatenating strings. You have to use the constructor: RegExp() to make a regex from a string.

Here is my function for matching an array:

   function matcharray(regexp, array) {
        var filtered = [];
        for (i = 0; i < array.length; i++) {
            if (regexp.test(array[i])) {
                filtered.push(array[i]);
            }
        }
        return filtered;
    }

You could call this function like so:

var myregex = "abc";
alert(matcharray(new RegExp(myregex), my_array).join());
发布评论

评论列表(0)

  1. 暂无评论