
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
Finding the Longest String in an Array in JavaScript
We are required to write a JavaScript function that takes in an array of strings. Our function should iterate through the array and find and return the longest string from the array.
Our function should do this without changing the content of the input array.
Example
The code for this will be −
const arr = ["aaaa", "aa", "aa", "aaaaa", "acc", "aaaaaaaa"]; const findLargest = (arr = []) => { if(!arr?.length){ return ''; }; let res = ''; res = arr.reduce((acc, val) => { return acc.length >= val.length ? acc : val; }); return res; }; console.log(findLargest(arr));
Output
And the output in the console will be −
aaaaaaaa
Advertisements