Rushaid
Rushaid

Reputation: 5

Counting words with a given length range

I have to Return the number of words in a sentence which has a number of characters between param min and max using JavaScript.

Length could include both min & max

for example, findWordsWithLengthRange("Life is about making an impact, not making an income", 6,8) Return value should equal to 4

Below is the function I tried.

function wordLengthCount(str, min, max) {

    var a = str.split(' ');

    var count=0;

    for(var i =0; i<a.length ; i++){

        if(a[i]>=min && a[i]=<max){

            count += 1;
        }
     }

     return count;
}

console.log(wordLengthCount("The weather is so good today", 2, 5));

The count is always 0 with the code above. The actual result in above should be 5

Upvotes: 0

Views: 809

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36574

You are just there. Just need to check the length of a[i] instead of element itself.

But you can also do that using filter()

const wordLengthCount = (str, min, max) => 
       str
        .split(' ')
        .filter(({length}) => length >= min && length <= max)
        .length 

console.log(wordLengthCount("The weather is so good today", 2, 5));

Upvotes: 0

Titus
Titus

Reputation: 22474

You are comparing a string with a number (eg: (a[i]>=min), you should compare the string's length (eg: (a[i].length >= min).

Here is a working version of your approach:

function wordLengthCount(str, min, max) {
  var a = str.split(' ');
  var count = 0;
  for (var i = 0; i < a.length; i++) {
    if (a[i].length >= min && a[i].length <= max) {
      count += 1;
    }
  }
  return count;
}

console.log(wordLengthCount("The weather is so good today", 2, 5));

Also, you've used =< which is invalid syntax, the greater then and less then symbols have to come before the equal sign.

Upvotes: 6

Related Questions