코플릿 기록/JavaScript

고차함수 16번

뭉지야 2023. 1. 15. 00:18
728x90

#문제

문자열을 요소로 갖는 배열을 입력받아 각 요소의 길이를 요소로 갖는 새로운 배열을 리턴해야 합니다.

arr.map이용해라


#예시

let output = getLengthOfElements(['', 'a', 'ab', 'abc']);
console.log(output); // --> [0, 1, 2, 3]

getLengthOfElements(['hello', 'code', 'states']);
console.log(output); // --> [5, 4, 6]

#정답

function getLengthOfElements(arr) {
  //각 요소의 길이를 요소로 갖는 새로운 배열
  return arr.map (el => el.length);

//  function으로 표현하면
  return arr.map(function (el) {
    return el.length;
  });
 
}
728x90