Viết hàm nhận mảng chứa các kiểu dữ liệu khác nhau, trả về Map thống kê tần suất từng kiểu (dùng typeof).
Ví dụ
Mảng: [23, 'df', undefined, null, 12, {name: 'Rajesh'}, [2,4,7], 'dfd', null, Symbol('*'), 8]
Giải pháp
Mã triển khai:
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 type = typeof val;
acc.set(type, (acc.get(type) || 0) + 1);
return acc;
}, new Map());
};
console.log(countDataTypes(arr));
Kết quả
Đầu ra trong console:
Map(5) {
'number' => 3,
'string' => 2,
'undefined' => 1,
'object' => 4, // null, object, array, array
'symbol' => 1
}
Lưu ý: typeof null === 'object', typeof [] === 'object'.