首页 > 解决方案 > 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

标签: javascript

解决方案


您不能真正对对象执行此操作,因为对象的所有键都是字符串或符号。非字符串或非符号键将被转换为字符串:

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()));


推荐阅读