JavaScript: Take any number of iterable objects or objects with a length property and returns the longest one
JavaScript fundamental (ES6 Syntax): Exercise-79 with Solution
Write a JavaScript program to take any number of iterable objects or objects with a length property and return the longest one.
- Use Array.prototype.reduce(), comparing the length of objects to find the longest one.
- If multiple objects have the same length, the first one will be returned.
- Returns undefined if no arguments are provided.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0];
console.log(longestItem('this', 'is', 'a', 'testcase'));
console.log(longestItem(...['a', 'ab', 'abc']));
console.log(longestItem(...['a', 'ab', 'abc'], 'abcd'));
console.log(longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]));
console.log(longestItem([1, 2, 3], 'foobar'));
Sample Output:
testcase abc abcd [1,2,3,4,5] foobar
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-79-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to invert the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.
Next: Write a JavaScript program to implement the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join