Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the shortest string in array

How can i find the shortest string in javascript array with different count of array elements? I used

var min = Math.min(arr[0].length,arr[1].length,arr[2].length);

and i have result like shortest string between 3 elements of array. But I don't want to care about numbers of elements

like image 993
Michael Shtefanitsa Avatar asked Nov 29 '16 11:11

Michael Shtefanitsa


People also ask

How do you find the shortest word in Java?

One of the approach to find smallest and largest word is to split string into words then, compare length of each word with variables small and large. If length of a word is less than length of small then, store that word in small. If length of a word is greater than length of large then, store that word in large.

How do you find the shortest length of a string in a list Python?

Use Python's built-in min() function with a key argument to find the shortest string in a list. Call min(lst, key=len) to return the shortest string in lst using the built-in len() function to associate the weight of each string—the shortest string will be the minimum.

How do you find the length of a string in Java?

To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class. In Java, strings are objects created using the string class and the length() method is a public member method of this class. So, any variable of type string can access this method using the . (dot) operator.


1 Answers

Use Array#reduce method.

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce(function(a, b) {
    return a.length <= b.length ? a : b;
  })
)

With ES6 arrow function

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce((a, b) => a.length <= b.length ? a : b)
)
like image 146
Pranav C Balan Avatar answered Oct 01 '22 10:10

Pranav C Balan