LoginSignup
1

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-12-14

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

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()

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1