DEV Community

phavourCodes
phavourCodes

Posted on • Edited on • Originally published at educative.io

How to find the shortest string in an array in JavaScript

TABLE OF CONTENTS

  • Introduction
  • The reduce() method
  • The forEach() method
  • The sort() method
  • Conclusion
  • Connect with me

When working with an array of strings in JavaScript, you may need to find the shortest string in an array, it can be for different reasons such as filtering or sorting out data and so on. In this article we will be exploring three easy methods used in finding the shortest string in a JavaScript array.

Method 1: using reduce()
The reduce() method is a pre-defined method in JavaScript that takes in an array and reduces it to a single value. This method takes in two arguments, the first argument is a callback function that iterates through the array and reduces that array down to one single value.
The callback function is executed on each element of the array and it takes in four arguments:

  1. accumulator (required)- is the accumulated value from previous iterations of the callback( ) function.
  2. currentValue (required)- the value of the current element being processed.
  3. currentIndex (optional)- the index of the current element.
  4. array (optional) - the array the reduce( ) method is called on

The initialValue - the reduce() method also takes an optional second parameter that represents the initial value of the accumulator, if provided the reduce( ) method starts with this initial value otherwise the first element of the array is used and reduction starts from the second element.

Syntax
array.reduce(function(accumulator,currentValue,currentIndex, arr), initialValue);

Example
Let's see how reduce() method works in the following coding example.

const subjects = ["Biology", "English", "Physics", "Maths","Chemistry"];
const reducedSubjects = subjects.reduce(function(a, b) {
  return a.length < b.length ? a : b;
});
console.log(reducedSubjects); // Maths
Enter fullscreen mode Exit fullscreen mode

Explanation
In the example above, we used the reduce() method to compare the length of each string in the array and returned the shortest string.
Line 3: The callback function takes in two arguments - the argument a, represents the accumulated value and b represents the current element being processed.
Line 4: Inside the callback function, the length of the accumulated value which is a is compared to the length of the current element which is b using the ternary operator(? :). if the length of a is less than the length of b, the callback function returns a otherwise b is returned.
The reduce( ) method iterates over the elements in the subjects array, at the end of each iteration, it updates the accumulator and returns the shorter value between the accumulated value a and the current element b.
Line 7: Prints the shortest string. From the example above, "Maths" is returned as the shortest string.

Method 2: using forEach()
The forEach() method is a pre-defined method in JavaScript that iterates over an array and executes a callback function on each element of the array. This method takes in one argument, a callback function that iterates through the array and this function takes in three arguments.

  1. currentValue (required)- the value of the current element being processed.
  2. index (optional)- the index of the current element.
  3. array (optional) - the array the forEach( ) method is called on. Using the forEach() method to find the shortest string in an array, we must keep track of the current shortest string by storing it in a variable.

Syntax

array.forEach(function(currentValue, index, arr), thisValue);

Example

const subjects = ["Biology", "English", "Physics", "Maths", "Chemistry"];
let shortestString = subjects[0];
subjects.forEach(function(value) {
  if(value.length < shortestString.length){
      shortestString = value;
  }
});

console.log(shortestString); // Maths
Enter fullscreen mode Exit fullscreen mode

Explanation
Line 3: we used the let keyword instead of const because we might reassign it. if the current value is shorter than the shortestString variable , it becomes the new shortest string and is assigned to the shortestString variable.
Lines 5-7: This method goes through every string in the array and compares the length of the current value to the length of the shortestString variable.
Line 7: From the example above, "Maths" is returned as the shortest string.

Method 3: using sort()
The sort() method is a pre-defined method in JavaScript that sorts the elements of an array and returns the sorted array. The sort() method does not take any argument. This method by default sorts the elements of the array in an ascending order.

compareFunction - defines the sort order.
For the purpose of this article, we used this method to sort the elements of the array by their length.

Syntax

array.sort(compareFunction);

Example

const subjects = ["Biology", "English", "Physics", "Maths", "Chemistry"];

subjects.sort(function(a, b) {
  return a.length - b.length;
});

console.log(subjects[0]); // Maths
Enter fullscreen mode Exit fullscreen mode

Explanation
Line 3: The sort( ) method is called on the subjects array and takes a compare function as argument.
Line 4: the compare function, subtracts the length of b from the length of the current element a to determine the order of the elements.
Line 7:After sorting, the shortest string will be at the beginning of the sorted array (index 0), which is now assigned to the shortestString variable.
Line 8: From the example above, the value of the shortestString "Maths" is returned in the console.

Conclusion
Finding the shortest string in an array in JavaScript involves iterating through the array by either using the reduce() method, forEach() method or the sort() method. Thanks for reading.

Connect with me
Follow me on LinkedIn Twitter GitHub to stay updated with my latest content as I continue to build and hone my skills in software engineering.

Top comments (0)