- 1

How to find the shortest word in JavaScript array using ES5?

30th Jul 2021, 12:37 PM
Saiful Emon
Saiful Emon - avatar
2 odpowiedzi
+ 3
var arr = ['cats', 'giants', 'daughters', 'ice']; var min = Math.min.apply(Math, arr.map(function(str) { return str.length; })); console.log(min); I mean seriously? If u don't know you could have just googled)) It took me literally 5 seconds...
30th Jul 2021, 12:44 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
function shortestWord(words) { const lengths = words.map(w =>w.length); // shortest length const min = Math.min(...lengths); const shortestObj = words.map(word => ({word, length: word.length})).find(wo => wo.length===min); // shortest word (first found) const shortest = shortestObj.word return shortest; } https://code.sololearn.com/cTermxi25lS2/?ref=app https://code.sololearn.com/ckIOvuXjpmbS/?ref=app
30th Jul 2021, 4:23 PM
Calviղ
Calviղ - avatar