在 JavaScript 中將資料型別從陣列中分離到組中
問題
我們需要編寫一個 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 ]
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP