在陣列中計算資料型別的數量 - JavaScript
我們需要編寫一個 JavaScript 函式,其中傳入的陣列包含不同資料型別的資料,並且該函式應當返回一個表示每種資料型別頻率的地圖。
假設我們的陣列如下所示 -
const arr = [23, 'df', undefined, null, 12, {
name: 'Rajesh'
}, [2, 4, 7], 'dfd', null, Symbol('*'), 8];示例
以下是程式碼 -
const arr = [23, 'df', undefined, null, 12, {
name: 'Rajesh'},
[2, 4, 7], 'dfd', null, Symbol('*'), 8];
const countDataTypes = arr => {
return arr.reduce((acc, val) => {
const dataType = typeof val;
if(acc.has(dataType)){
acc.set(dataType, acc.get(dataType)+1);
}else{
acc.set(dataType, 1);
};
return acc;
}, new Map());
};
console.log(countDataTypes(arr));輸出
以下是控制檯中的輸出 -
Map(5) {
'number' => 3,
'string' => 2,
'undefined' => 1,
'object' => 4,
'symbol' => 1
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP