

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding all the longest strings from an array in JavaScript
Suppose, we have an array of strings like this −
const arr = [ 'iLoveProgramming', 'thisisalsoastrig', 'Javascriptisfun', 'helloworld', 'canIBeTheLongest', 'Laststring' ];
We are required to write a JavaScript function that takes in one such array of strings. The purpose of our function is to pick all the longest string (if there are more than one).
The function should finally return an array of all the longest strings in the array.
Example
Following is the code −
const arr = [ 'iLoveProgramming', 'thisisalsoastrig', 'Javascriptisfun', 'helloworld', 'canIBeTheLongest', 'Laststring' ]; const getLongestStrings = (arr = []) => { return arr.reduce((acc, val, ind) => { if (!ind || acc[0].length < val.length) { return [val]; } if (acc[0].length === val.length) { acc.push(val); } return acc; }, []); }; console.log(getLongestStrings(arr));
Output
Following is the output on console −
[ 'iLoveProgramming', 'thisisalsoastrig', 'canIBeTheLongest' ]
- Related Questions & Answers
- Finding the longest string in an array in JavaScript
- Finding all possible combinations from an array in JavaScript
- Finding the longest common consecutive substring between two strings in JavaScript
- Finding the longest substring uncommon in array in JavaScript
- Finding the nth missing number from an array JavaScript
- Finding all possible subsets of an array in JavaScript
- Finding matching pair from an array in JavaScript
- Finding the longest valid parentheses JavaScript
- JavaScript Return an array that contains all the strings appearing in all the subarrays
- Finding even length numbers from an array in JavaScript
- Longest possible string built from two strings in JavaScript
- Finding all peaks and their positions in an array in JavaScript
- Finding longest consecutive joins in JavaScript
- C# Program to find the longest string from an array of strings using Lambda Expression
- Finding the rotation of an array in JavaScript
Advertisements