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
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.
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.
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.
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With