- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find longest string in array (excluding spaces) JavaScript
We are required to write a function that accepts an array of string literals and returns the index of the longest string in the array. While calculating the length of strings we don’t have to consider the length occupied by whitespaces
If two or more strings have the same longest length, we have to return the index of the first string that does so.
We will iterate over the array, split each element by whitespace, join again and calculate the length, after this we will store this in an object. And when we encounter length greater than currently stored in the object, we update it and lastly, we return the index.
Example
const arr = ['Hello!', 'How are you', 'Can ', 'I use', 'splice method with', ' strings in Js?']; const findLongestIndex = (arr) => { const index = { '0': 0 }; const longest = arr.reduce((acc, val, index) => { const actualLength = val.split(" ").join("").length; if(actualLength > acc.length){ return { index, length: actualLength }; } return acc; }, { index: 0, length: 0 }); return longest.index; }; console.log(findLongestIndex(arr));
Output
The output in the console will be −
4
- Related Articles
- Finding the longest string in an array in JavaScript
- Find number of spaces in a string using JavaScript
- Get the longest and shortest string in an array JavaScript
- Remove extra spaces in string JavaScript?
- Average of array excluding min max JavaScript
- Finding number of spaces in a string JavaScript
- Find the Length of the Longest possible palindrome string JavaScript
- Length of longest string chain in JavaScript
- Removing all spaces from a string using JavaScript
- Longest string with two distinct characters in JavaScript
- Finding the longest word in a string in JavaScript
- Find the shortest string in an array - JavaScript
- Longest string consisting of n consecutive strings in JavaScript
- Longest possible string built from two strings in JavaScript
- Finding the longest substring uncommon in array in JavaScript

Advertisements