문자열을 받아 문자열에서 가장 짧은 단어를 반환하는 JavaScript 함수를 작성해야 합니다.
예:입력 문자열이 -
인 경우const str = 'This is a sample string';
그러면 출력은 다음과 같아야 합니다. -
const output = 'a';
예시
이에 대한 코드는 -
const str = 'This is a sample string';
const findSmallest = str => {
const strArr = str.split(' ');
const creds = strArr.reduce((acc, val) => {
let { length, word } = acc;
if(val.length < length){
length = val.length;
word = val;
};
return { length, word };
}, {
length: Infinity,
word: ''
});
return creds.word;
};
console.log(findSmallest(str)); 출력
콘솔의 출력 -
a