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.
If targeting ES3 (the version of javascript that is most common, and safe to use) then use
But if you are targeting ES5 then you can do it using
If you want to you can include the ES5 filter method in ES3 by using
See https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/filter#Compatibility for more.
UPDATE
Answer for the updated question