The task is to ask the user text of arbitrary length; find the three longest words in the entered text. So I requested the text, broke the words in the array, removed the extra commas, even created a new array with word lengths. In essence, the task is to find the 3 largest from an array of numbers.

var text = prompt('Введите любой произвольный текст', 'Футбол это игра, целью которой является забить мяч в ворота противника'); var textArr = text.split(' '); for (i = 0; i < textArr.length; i++) { textArr[i] = textArr[i].replace(',', ''); }; var textArrLength = []; for (i = 0; i < textArr.length; i++) { textArrLength[i] = textArr[i].length; }; 

    1 answer 1

    You can use the custom function to sort the array, sort by length and take the first 3:

     var text = 'Футбол это игра, целью которой является забить мяч в ворота противника'; var textArr = text.split(' '); var newArr = textArr.sort(compare); console.log('Три самые длинные слова : ' + newArr[0] + ' ' + newArr[1] + ' ' + newArr[2]); function compare(a, b) { if (a.length > b.length) { return -1; } if (a.length < b.length) { return 1; } return 0; } 

    You can read about sorting arrays here

    • Thank you, class! - PolonskiyP
    • @PolonskiyP is not, if the answer came up, check the box on the left so that you can see that it’s resolved. - Rostyslav Kuzmovych
    • and here: stackoverflow.com/a/432370/178988 . Only sorting in order to select maximum elements is not very good. // cc @PolonskiyP - Qwertiy