[JavaScript] How to get a shortest string from an array?
I want to find the shortest string (in terms of length) from an array, How can I do that in Javascript?
2 Answers
4 years ago by Jahaan
var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];
console.log(
arr.reduce(function(a, b) {
return a.length <= b.length ? a : b;
})
)
// output a
4 years ago by Nazim Ahmed
You can use either of the below solutions to find the shortest string present in an array
Method: 1
array.reduce((a, b) => a.length <= b.length ? a : b)
Method: 2
array.sort((a, b) => a.length - b.length)[0]
Try running the above solutions here : https://onecompiler.com/javascript/3xn6q75vx
4 years ago by Meera