longestWord.js (7kyu 61)

Codewars 알고리즘 풀이


Problem

  • When given a string of space separated words, return the word with the longest length.
    • 공백으로 분리된 문자열에서, 가장 긴 단어를 반환한다.
  • If there are multiple words with the longest length, return the last instance of the word with the longest length.
    • 가장 긴 단어가 여러 개인 경우, 마지막 instance를 반환한다.


Solution 01

function longestWord(str) {
  str = str.split(' ');
  let result = '';
  
  for (let i = 0; i < str.length; i++) {
    if (result.length <= str[i].length) {
      result = str[i];
    }
  }
  return result;
}

longestWord('one two three');       // three
longestWord('one two three four');  // three
longestWord('one two six ten');     // ten

split(): 문자열을 부분 문자열로 분할하고, 새 배열로 반환한다.


Solution 02

function longestWord(str) {
  return str.split(' ').sort((a, b) => a.length - b.length).pop();
}

longestWord('one two three');       // three
longestWord('one two three four');  // three
longestWord('one two six ten');     // ten

sort(): 배열의 element를 정렬한 후, 그 배열을 반환한다.

pop(): 배열의 마지막 element를 제거하고, 그 element를 반환한다.


Solution 03

function longestWord(str) {
  return str.split(' ').reduce((result, i) => result.length <= i.length ? i : result, '');
}

longestWord('one two three');       // three
longestWord('one two three four');  // three
longestWord('one two six ten');     // ten

reduce(): 배열을 하나의 값으로 줄이고, 그 값을 반환한다.