Returning lengthy words from a string using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a sentence of words and a number. The function should return an array of all words greater than the length specified by the number.

Input

const str = 'this is an example of a basic sentence';
const num = 4;

Output

const output = [ 'example', 'basic', 'sentence' ];

Because these are the only three words with length greater than 4.

Example

Following is the code −

 Live Demo

const str = 'this is an example of a basic sentence';
const num = 4;
const findLengthy = (str = '', num = 1) => {
   const strArr = str.split(' ');
   const res = [];
   for(let i = 0; i < strArr.length; i++){
      const el = strArr[i];
      if(el.length > num){
         res.push(el);
      };
   };
   return res;
};
console.log(findLengthy(str, num));

Output

[ 'example', 'basic', 'sentence' ]
raja
Published on 17-Apr-2021 11:50:28
Advertisements