How to use forEach and an empty array In Javascript
In this approach, we initialize an empty array and iterate over each word in the input string using forEach. For each of the words that is greater than the k value is pushed into the result array and printed as the output.
Syntax:
let res = [];
str.split(" ").forEach(word => word.length > k && result2.push(word));
result2.join(" ");
Example: The below example uses forEach and empty array to find words that are greater than the given length k in JavaScript.
Javascript
let str = "hello geeks for geeks is computer science portal" ; let k = 4; let res = []; str.split( " " ).forEach(word => { if (word.length > k) { res.push(word); } }); console.log(res.join( " " )); |
Output
hello geeks geeks computer science portal
JavaScript Program to Find Words which are Greater than given Length k
In JavaScript, to find words that are greater than the given length k, we need to split an array into words and then filter out words based on their lengths.
Table of Content
- Using split and filter methods
- Using forEach and an empty array
- Using RegEx