0

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; i<arr.length; i++){
    if(arr[i].match(/^[a-z]{3}$/)){
        console.log(arr[i])
    }
}

//returns: "cat" and "dog"

Or is there already a built-in function that does the job for me, so I don't have to explicitly define a for-loop and and if-statement.

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • 2
    How about just checking the `.length` of each string? – Pointy Feb 17 '16 at 22:58
  • 1
    It's more about working with regex and arrays. What kind of regex will be executed is less important in my example. – Evgenij Reznik Feb 17 '16 at 22:59
  • 1
    Maybe you could use `RegRxp.test(string)`, see [*regex.test V.S. string.match to know if a string matches a regular expression*](http://stackoverflow.com/questions/10940137/regex-test-v-s-string-match-to-know-if-a-string-matches-a-regular-expression). – Wiktor Stribiżew Feb 17 '16 at 23:00
  • 1
    So you want to use a regular expression for the sake of using aregular expression? OK. – Pointy Feb 17 '16 at 23:01
  • @Pointy: OP does not want to return `$1$` strings. – Wiktor Stribiżew Feb 17 '16 at 23:01
  • @Pointy: I'm looking for the most efficient way to process an array with regex. What kind of regular expression it will be (finding <=3 words; finding all words starting with an a, etc.) is not important. This was just an example. – Evgenij Reznik Feb 17 '16 at 23:03
  • 2
    @user1170330 no, you're not. your question clearly states you want all elements in an array with some kind of length restriction. This has nothing to do with needing regexp; just use `filter`, it's baked into JS and has been for years. – Mike 'Pomax' Kamermans Feb 17 '16 at 23:04
  • How about editing the question to say "What's the most cpu-efficient way to process an array with regex?" Then you'll avoid having to explain that you really don't care about the length of the array elements. – Jonathan M Feb 17 '16 at 23:06
  • The questions is unclear as it's written. The part about the length is largely irrelevant (as per your comments). – Evan Trimboli Feb 17 '16 at 23:10

5 Answers5

3

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}$/);
});
Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
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

Gabs00
  • 1,869
  • 1
  • 13
  • 12
  • +1 for answering the OP with a regular expression, without a for loop, and using a regex which can be arbitrarily changed from a length check to any other regex validation method that he may need to implement. – OnlineCop Feb 17 '16 at 23:11
1

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.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

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);
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
0

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);
linuxdan
  • 4,476
  • 4
  • 30
  • 41