在 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