Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@may88seiji

js 一番文字の多い単語を見つける

配列の中から一番文字数の大きい単語をみつけてその数を返す

script.js
function findLongestWord(s) {
 //write your code.
}
findLongestWord("The quick brown fox jumped over the lazy dog");

出力結果 例

script.js
("May the force be with you")// 5
("Google do a barrel roll") //6
("What is the average airspeed velocity of an unladen swallow")// 8
("What if we try a super-long word such as otorhinolaryngology")//19

一番最初に試したコード

script.js
function findLongestWord(s) {
  var i = s.split(' ');
  var b = i[0];
  for( var a = 0; a < i.length; a++){
    if( b.length<i[a].length){
      b = i[a];
    }
  }
  return b.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

教えていただいたコード

script.js
function findLongestWord(str) {
  var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
  return longestWord[0].length;
}

考え方

str.split(' ')で単語に切り分ける。
.sort(function(a,b){ return b.length - a.length; }
で配列に文字数の多い単語順にならべかえる。
{ return a.length - b.length; }にすると少ない順になる。
並べ替えた単語の添字0を返り値にすると一番文字の多い単語の数値を取得できる。

別のコードを思いついた方、コメントお待ちしてます。

参考リンク

.sort()

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?