简体   繁体   English

循环遍历并获取数组中所有元素的频率

[英]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.我正在遍历一个[2,2,"2","2",4,4]数组,所以我在这里计算每个元素的频率,然后将元素存储为对象中的键,并将其频率存储为那个对应的键。

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现在 console.log 这里给出

{2: 2, 4: 2} {2: 2, 4: 2}

what i want was我想要的是

{2:2,2:2,4:2} {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由于我有两个字符串类型的“2”和两个类型编号的 2,我想将它们视为对象中的单独键,因为我必须考虑它们的类型单独计算其频率

You can't really do this with an object, since all keys of objects either strings or symbols.你不能真正用一个对象来做这件事,因为对象的所有键都是字符串或符号。 A non-string or non-symbol key would be converted to a string instead:非字符串或非符号键将被转换为字符串:

 const obj = {}; obj["42"] = 1; obj[42] = 2; console.log(obj)

If you want to keep the type intact, you can use a Map which does not have this limitation for its keys:如果要保持类型不变,可以使用对其键没有此限制的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()));

The Object keys in javascript behave like "strings". javascript 中的对象键的行为类似于“字符串”。 Also, in an object two keys cannot be the same.此外,在一个对象中,两个键不能相同。

This is the reason why your code is not working.这就是您的代码不起作用的原因。

In object literal terms, b is a property.在对象字面意义上, b是一个属性。 Properties are either strings or symbols in JavaScript, although when defining the property name inside an object literal you may omit the string delimiters.属性在 JavaScript 中可以是字符串或符号,但在对象字面量中定义属性名称时,您可以省略字符串分隔符。

for (key in a) {
    alert(typeof key);
    //-> "string"
}

You should use a Map instead of an object.您应该使用Map而不是对象。 Objects coerce keys into strings.对象将键强制转换为字符串。 Maps can use objects or primitives.地图可以使用对象或基元。

 const frequencies = arr => arr.reduce((m, e) => m.set(e, (m.get(e) || 0) + 1), new Map()) const data = [2, 2, '2', '2', 4, 4] const result = frequencies(data) console.log(result) // Map { 2 => 2, '2' => 2, 4 => 2 }

If you have to use an object you could do something like the next two examples.如果你必须使用一个对象,你可以像接下来的两个例子那样做一些事情。

You can make a key by combining type and value:您可以通过组合类型和值来制作键:

 const key = x => `${typeof x} ${x}` const frequencies = arr => arr.reduce( (o, e) => ({ ...o, [key(e)]: (o[key(e)] || 0) + 1, }), {} ) const data = [2, 2, '2', '2', 4, 4] const result = frequencies(data) console.log(result)

Or, nest the frequency counts in type properties:或者,在类型属性中嵌套频率计数:

 const frequencies = arr => arr.reduce((o, e) => { const type = typeof e o[type] = o[type] || {} o[type][e] = (o[type][e] || 0) + 1 return o }, {}) const data = [2, 2, '2', '2', 4, 4] const result = frequencies(data) console.log(result)

As the key is "2" it will be overridden for the occurrences on String and number.由于键是“2”,它将被字符串和数字上的出现覆盖。

You can check the occurrences as follow您可以按如下方式检查事件

 let countobjet = {}; let array = [2, 2, "2", "2", 4, 4]; for (i = 0; i < array.length; i++) { let count = 0 for (j = 0; j < array.length; j++) { if (typeof array[i] === 'string' && typeof array[j] === 'string' && array[i] === array[j]) { count++; } else if (typeof array[i] === 'number' && typeof array[j] === 'number' && array[i] === array[j]) { count++; } } if (typeof array[i] === 'string') countobjet[array[i] + '_str'] = count; else countobjet[array[i]] = count; } console.log(countobjet)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM