javascript - Select Objects in Array Based on Regex Match -


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

For example, if I have ['apple', 'avacado', 'banana', 'cherry'] and only need the output function to start with 'A'.

Edit:

Function filters ABC (arr, abc)

   

Var arr = arr Var filtered = (function () {var filtered = [], i = arr.length; while (i--) {if ('/ ^' + abc + '/'.test(arr[i])) {filter Push (ARR [I]);}} return filtered;}) (); Return filtered.joint ();

}

Try to call it with filter ABC (ARI, A) or filter ABC (AR, 'A | B | C |') In C, but there is trouble with this part.

If target is ES3 (Javascript is the most common and safe to use) 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 ]);}} Filtered back;}) (); Warning (filtered.join ());  

But if you are targeting ES5, then you can call it

  var filtered = arr.filter (function (item) {return / ^ A / Items for use); }); Warning (filtered.join ());  

If you want to include ES3 filter method in ES3 by using

 , then (Array.prototype.filter ) {Array.prototype Filter = function (fun / *, isp * /) {var len = this.length & gt; & Gt; & Gt; 0; If (type of fun! = "Function") throw a new type error (); Var res = []; Var thisp = logic [1]; (Var i = 0; i & lt; len; i ++) {if (in this) {var val = this [i]; // If fun changes this mute (fun call (app, val, i, this)) res.push (val); }} Return Ridge; }; }  

See more.

UPDATE An answer to the updated question

  var filtered = (function (pattern) {var filtered = [], i = arr Length, re = new RegExp ('^' + pattern), while (i--) {if (re.test (arr [i])) {Filters Push (ARE [I]);}} filtered forward;} ) ('a'); // A pattern is warning (filtered.join ());  

Comments