문제
혼합 데이터 유형의 배열을 취하는 JavaScript 함수를 작성해야 합니다. 함수는 데이터 유형 이름을 키로 포함하고 해당 값을 배열에 있는 특정 데이터 유형의 요소 배열로 포함하는 개체를 반환해야 합니다.
예시
다음은 코드입니다 -
const arr = [1, 'a', [], '4', 5, 34, true, undefined, null];
const groupDataTypes = (arr = []) => {
const res = {};
for(let i = 0; i < arr.length; i++){
const el = arr[i];
const type = typeof el;
if(res.hasOwnProperty(type)){
res[type].push(el);
}else{
res[type] = [el];
};
};
return res;
};
console.log(groupDataTypes(arr)); 출력
다음은 콘솔 출력입니다 -
{
number: [ 1, 5, 34 ],
string: [ 'a', '4' ],
object: [ [], null ],
boolean: [ true ],
undefined: [ undefined ]
}