简体   繁体   English

计算JavaScript数组中对象的出现次数

[英]Count occurrences of objects in JavaScript array

I have an array of objects like this: 我有一个这样的对象数组:

arrayOfObjs = [{1:"h"}, {1:"h"}, {2:"h"}, {3:"ha"}, {4:"haa"}, {4:"haa"}, {4:"haa"}]

I'd like to count the occurrence of each object, and get the result back in a sorted, iterable data structure, like this: 我想计算每个对象的出现次数,并将结果返回到经过排序的可迭代数据结构中,如下所示:

{
  {4:"haa"}: 3,
  {1:"h"}: 2,
  {2:"h"}: 1,
  {3:"ha"}: 1
}

The keys can even be in arrays. 键甚至可以是数组。 I tried using Lodash's countBy function on arrayOfObjs. 我尝试在arrayOfObjs上使用Lodash的countBy函数。 However, this simply resulted in 但是,这仅仅是导致

{[object Object]:5}

Any libraries/functions I can use to get this job done? 我可以使用任何库/函数来完成这项工作吗? Something similar to Python's Counter 类似于Python的Counter

UPDATE 更新

As an alternative, I tried to organize my array like this: 作为替代方案,我尝试按以下方式组织数组:

array = [[1,"h"], [1,"h"], [2,"h"], [3,"ha"], [4,"haa"], [4,"haa"], [4,"haa"]];

Again used Lodash's countBY function, and my result was: 再次使用Lodash的countBY函数,结果是:

{1,h: 2, 2,h: 1, 3,ha: 1, 4,haa: 3}

Which is a bit better , but I now I have to use regular expressions to split apart each key of the object, since "1, h" is a string. 更好一点 ,但是我现在必须使用正则表达式将对象的每个键分开,因为“ 1,h”是一个字符串。 Not ideal :( 不理想:(

Ideally , I'd like my keys to be either objects, or arrays, or something of the sort. 理想情况下 ,我希望我的键既可以是对象,也可以是数组,或类似的东西。

 arrayOfObjs = [{1:"h"}, {1:"h"}, {2:"h"}, {3:"ha"}, {4:"haa"}, {4:"haa"}, {4:"haa"}]; var hash = {}; arrayOfObjs.forEach(function(item){ var key = JSON.stringify(item); if (hash[key]) { hash[key]++; } else { hash[key] = 1; } }); console.log(hash); var hash2 = {}; arrayOfObjs.forEach(function(item){ var key = JSON.stringify(item); if (hash2[key]) { hash2[key]++; } else { hash2[key] = 1; } }); for (key in hash2) { val = hash2[key]; console.log(key, val); } 

Note, that insted of hash[key] you could use hash[item] , you just won't see it the way you expect by console.log(hash) 注意,使用hash[key]可以使用hash[item] ,但不会像console.log(hash)那样看到它。

Shameless Plug: 无耻的插头:

I am working on a library called Pro.js that has a collections module that does all sorts of neat things. 我正在一个名为Pro.js的库中工作,该库具有一个收集模块,可以完成各种巧妙的工作。 The enumerable class has a .groupBy() method that would be particularly useful here. 可枚举的类具有.groupBy()方法,在此特别有用。

var arrayOfObjs = [{1:"h"}, {1:"h"}, {2:"h"}, {3:"ha"}, {4:"haa"}, {4:"haa"}, {4:"haa"}];
var enumerable = pro.collections.asEnumerable(arrayOfObjs);
var grouped = enumerable.groupBy(function(o) {
    return JSON.stringify(o);
});
var composites = grouped.select(function(g) {
    return {
        key: g[0],
        count: g.length,
        group: g
    };
});
var output = composites.toArray();

You can go to the Pro.js GitHub Page and use your developer tools to test out the library. 您可以转到Pro.js GitHub页面并使用开发人员工具测试该库。 Run the code snippet that I posted in the answer on the page and see if it produces a likeable result for you. 运行我在页面答案中发布的代码段,看看它是否为您带来满意的结果。

I decided this task using _.countBy, _.map and _.reduce 我决定使用_.countBy,_。map和_.reduce来完成此任务

arrayOfObjs = [{1:"h"}, {1:"h"}, {2:"h"}, {3:"ha"}, {4:"haa"}, {4:"haa"}, {4:"haa"}];

var a = _.countBy(arrayOfObjs, function (obj) {
    return _.map(obj, function (value, key) {
    return key + ' ' + value;
  });
})

b = _.reduce(a, function (result, value, key) {
    var splittedKey = key.split(' ');
  var newObj = {};

  newObj[splittedKey[0]] = splittedKey[1];

  var newKey = JSON.stringify(newObj)
  var resultObj = {};

  resultObj[newKey] = value;
  result.push(resultObj)

  return result;
}, []);

console.log(b)

https://jsfiddle.net/tkv94whe/ https://jsfiddle.net/tkv94whe/

You can try something like this: 您可以尝试如下操作:

 var arrayOfObjs = [{1:"h"}, {1:"h"}, {2:"h"}, {3:"ha"}, {4:"haa"}, {4:"haa"}, {4:"haa"}] var result = {}; arrayOfObjs.forEach(function(item){ var objStr = JSON.stringify(item); result[objStr] = result[objStr]? ++result[objStr]: 1; }); console.log(result); 

You can iterate over your array and use JSON.stringify() to convert objects to string and then compare them. 您可以遍历数组并使用JSON.stringify()将对象转换为字符串,然后进行比较。 Its simple hashmap technique that can be used then. 然后可以使用它的简单哈希图技术。

arrayOfObjs = [{1:"h"}, {1:"h"}, {2:"h"}, {3:"ha"}, {4:"haa"}, {4:"haa"}, {4:"haa"}];
    var result={}
    for(var i=0;i<arrayOfObjs.length;i++){
        if(!result[JSON.stringify(arrayOfObjs[i])]){
        result[JSON.stringify(arrayOfObjs[i])]=1;
      } else {
        result[JSON.stringify(arrayOfObjs[i])]=result[JSON.stringify(arrayOfObjs[i])]+1;
      }
    }
    console.log(result);

https://jsfiddle.net/xv22v72v/ https://jsfiddle.net/xv22v72v/

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

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