Skip to content Skip to sidebar Skip to footer

Regex And Array: Most Efficient Approach

I want to get all words with <=3 letters from an array. Is iterating the array and checking every entry an efficient approach? arr = ['cat', 'apple', 'window', 'dog']; for(i=0;

Solution 1:

No need to regex, try this:

var arr = ["cat", "apple", "window", "dog"];
var len = arr.length;

for(len; len<=0; len--){
    if(arr[len].length <= 3){
        console.log(arr[len]);
    }
}

Edit: If you don't want to explicitly define a for-loop and and if statement then try using .filter() and .match():

var arr = ["cat", "apple", "window", "dog"];
var AcceptedItems = arr.filter(function(item) {
    return item.match(/^[a-z]{1,3}$/);
});

Solution 2:

I assume you want to return words that are even like '1abc' since it has only 3 letters.

The below will work, using filter function of an array.

arr = ["cat", "apple", "window", "dog", "1acb", "1abcd"];

function getLessThanThree(anArray){
    return anArray.filter(function(v){
        return !( /[a-zA-Z]{3}./.exec(v) );
    })
}

console.log(getLessThanThree(arr)); // logs [ 'cat', 'dog', '1acb' ]

Test it here


Solution 3:

If you want to get items matching something in array you need to iterate it.

Anyway, since ECMA-Script 5 you would refactor your code as follows:

var results = arr.filter(function(item) { return item.lengh <= 3; });

Or in ECMA-Script 6 and above:

var results = arr.filter(item => item.length <= 3);

In terms of productivity, you're going to be faster.


Solution 4:

You're in JavaScript. It can already do this, no regexp required.

var arr = ["cat", "apple", "window", "dog"];
var filtered = arr.filter(function(e) { return e.length <= 3; });

done. Use ES6 for even simpler syntax:

var filtered = arr.filter(e => e.length <= 3);

Solution 5:

Lots of ways to skin this cat, I like:

var arr = ["cat", "apple", "window", "dog"];
var upToThreeLetters = function(word) {
  return word.length <= 3;
}
var filteredArr = arr.filter(upToThreeLetters);

Post a Comment for "Regex And Array: Most Efficient Approach"