Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした