javascript - Looping through and getting frequency of all the elements in an array
问题描述
I am looping through an array which is [2,2,"2","2",4,4]
so i am calulating frequency of each elements here and then storing the element as key in object and its frequency as a value of that corresponding key.
So below is the code for that
let countobjet={},r=[]
for(i=0;i<array.length;i++){
let count=0
for(j=0;j<array.length;j++){
if(array[i]===array[j]){count++
}
}
countobjet[array[i]]=count
}
console.log(countobjet)
Now console.log here gives
{2: 2, 4: 2}
what i want was
{2:2,2:2,4:2}
as i have two "2" of type string and two 2 of type number, i want to treat them as seperate key in the object cause i have to calulate its frequency seperately considering their type
解决方案
您不能真正对对象执行此操作,因为对象的所有键都是字符串或符号。非字符串或非符号键将被转换为字符串:
const obj = {};
obj["42"] = 1;
obj[42] = 2;
console.log(obj)
如果要保持类型完整,可以使用对其键没有此限制的Map :
const array = [2,2,"2","2",4,4];
let countobjet = new Map(),
r = []
for (i = 0; i < array.length; i++) {
let count = 0
for (j = 0; j < array.length; j++) {
if (array[i] === array[j]) {
count++
}
}
countobjet.set(array[i], count)
}
for(let [key, value] of countobjet.entries()) {
console.log(`For key ${key} of type ${typeof key}, count is: ${value}`)
}
console.log(Array.from(countobjet.entries()));
推荐阅读
- java - Android 工具栏菜单项保持为空
- python - Binance API client.get_order_book(symbol='ADAUSDT' in Python
- stripe-payments - 在结帐时分割多个订阅的最佳方法?
- google-cloud-platform - 带有 .Net Core 3.1 MVC 应用程序的 Google App Engine - 控制器之间的会话数据丢失
- awk - 使用 awk 替换每一行中的某些字段
- python - 如何检测并重新运行程序运行时使用的函数?
- laravel - 如何在控制器 laravel 中调用广播通知?
- workflow - 请帮我创建服务目录工作流
- visual-studio-code - 加速 launch.json 中的断点
- python - Python Slack Bot 对话框 - 连接问题