Find Longest, Shortest, and Random String in Array in Javascript

1. Find Longest String in Array

Here I define an array list of six elements and we can see the Longest string is “Performance”. So run this script to get an answer.

To Find the string we use reduce(). The reduce() the method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. Apart from this, there are many other methods by which you can get the same result.

var arrayList = ["Elements", "Console", "Sources", "Performance", "Network", "Memory"];
var longest_string = arrayList.reduce(function(a, b) { 
  return a.length > b.length ? a : b
}, '');


console.log(longest_string);

Result

Performance

2. Find Shortest String in Array

To find the shortest string in the array we use the same reduce() method.

 var arrayList  = ["Elements", "Console", "Sources", "Performance", "Network", "Memory"];
        var shortest_string =   arrayList.reduce(function(a, b) {
            return a.length <= b.length ? a : b;
        })

        
console.log(shortest_string);

Result

Memory

3. Find Random String from Array in Javascript

Here I use Math.random() and Math. floor () approach to find random string.

<script>
var myArray = [
    "One",
    "Two",
    "Three",
    "Four",
    "Five",
    "Six",
    "Seven",
    "Eight",
    "Nine",
    "Ten"
    ];

    var randomItem = myArray[Math.floor(Math.random()*myArray.length)];

        console.log(randomItem);
</script>

Result

You will random string

I hope it helps you.