Longest Item in Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of finding the longest item in an array using JavaScript. We will use the reduce() method to compare the length of objects in an array and return the longest one. This lab will provide a practical understanding of how to work with arrays and higher-order functions in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28475{{"`Longest Item in Array`"}} javascript/data_types -.-> lab-28475{{"`Longest Item in Array`"}} javascript/arith_ops -.-> lab-28475{{"`Longest Item in Array`"}} javascript/comp_ops -.-> lab-28475{{"`Longest Item in Array`"}} javascript/higher_funcs -.-> lab-28475{{"`Longest Item in Array`"}} javascript/spread_rest -.-> lab-28475{{"`Longest Item in Array`"}} end

How to Find the Longest Item in an Array

To find the longest item in an array, open the Terminal/SSH and type node. The function takes any number of iterable objects or objects with a length property and returns the longest one. It uses Array.prototype.reduce() to compare the length of objects and find the longest one. If multiple objects have the same length, the function returns the first one. If no arguments are provided, it returns undefined.

Here is the code:

const longestItem = (...vals) =>
  vals.reduce((a, x) => (x.length > a.length ? x : a));

You can use the function like this:

longestItem("this", "is", "a", "testcase"); // 'testcase'
longestItem(...["a", "ab", "abc"]); // 'abc'
longestItem(...["a", "ab", "abc"], "abcd"); // 'abcd'
longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
longestItem([1, 2, 3], "foobar"); // 'foobar'

Summary

Congratulations! You have completed the Longest Item in Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like