Colin Craft
Colin Craft

Reputation: 11

Javascript function for returning strings in an array that are longer than defined number

I am trying to write a function that takes an array of strings and a number that returns the strings in an array that are a longer length than the defined number.

Below is the code that I have started with:

var words = ["Harold", "hen", "asdasda"];

var i = 5
words.sort(function filterLongWords(x , i){
    if (words[x].length > i){
        return words[x];
    }
    else {
        console.log("You have no words longer than the number " + i + ".");
    }
}); 

Thanks!

Upvotes: 1

Views: 1348

Answers (1)

Amit Joki
Amit Joki

Reputation: 59292

You can just do what you intend to using Array.filter and Array.length

var longWords = words.filter(function(str) { return str.length > i; });
if (longWords.length == 0) {
  console.log("You have no words longer than the number " + i + ".");
}

Upvotes: 1

Related Questions