
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Returning Lengthy Words from a String Using JavaScript
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 −
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' ]
Advertisements