计算非常大的数组中的字符串实例,并将值添加到哈希值



我在一个数组中有一个非常大的单词数组,我想计算所有这些单词并将计数作为值添加到每个字符串中。

所以我举个例子:

words = ["a", "hello", "hello", "b", "went", "a"]

我想将其转换为:

words = [{"a" => 2}, {"b" => 1}, {"hello" => 2}, {"went" => 1}]

我已经看到了简单地计算字符串中的一个单词并返回其出现次数的方法,但是我如何大规模地做到这一点,同时创建一个具有出现次数的哈希数组?

我可以在之后删除重复值,我对计算值并将计数添加为哈希中的值的过程更感兴趣。

在第一回合中,您可以使用数组值和出现次数创建一个对象。然后遍历它以创建对象数组

var words = ["a", "hello", "hello", "b", "went", "a"];
var rObj = {};
var finalArray = [];
words.map(function(currentValue, index) {
  if (rObj.hasOwnProperty(currentValue)) {
    rObj[currentValue] = rObj[currentValue] + 1;
  } else {
    rObj[currentValue] = 1
  }
});
for (var keys in rObj) {
  var obj = {};
  obj[keys] = rObj[keys];
  finalArray.push(obj)
};
console.log(finalArray)

您可以

先使用 reduce() 来计数元素并返回对象,然后map()返回对象值数组。

var words = ["a", "hello", "hello", "b", "went", "a"]
var count = words.reduce(function(r, e) {
  if(!r[e]) r[e] = {[e]: 1}
  else r[e][e] += 1
  return r;
}, {})
var result = Object.keys(count).map(e => count[e])
console.log(result)

对于一个非常大的数组,我建议使用for循环的while和简单的检查带有单词的键是否存在。如果没有,则为其分配零。稍后递增计数对象的属性。

最后将对象转换为具有所需结构的数组。

var words = ["a", "hello", "hello", "b", "went", "a"],
    w,
    i = words.length,  
    count = Object.create(null),
    result;
    
while (i--) {
    w = words[i];
    if (!count[w]) {
        count[w] = 0;
    }
    count[w]++;
}
result = Object.keys(count).map(function (k) {
    var temp = {};
    temp[k] = count[k];
    return temp;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

不要通过哈希来计算中继器。使用 while 循环来减少开销。分配超过计算。您将获得快 5 倍数量级的答案。在 1/5 的时间内从 12 个单词中随机生成 100 万个单词。

var wordsArray = ['apple', 'beer', 'cake', 'potato', 'orange', 'monitor', 'program', 'application', 'keyboard', 'javascript', 'gaming', 'network'],
  words = [];
for (i = 0; i < 1000000; i++) {
  words.push(wordsArray[Math.floor(Math.random() * wordsArray.length)]);
}
function getCount(words) {
  var w,
    i = words.length,
    hash = {};
  while (i--) {
    w = words[i];
    if (!hash[w]) {
      hash[w] = 0;
    }
    hash[w]++;
  }
  return hash
}
console.time('Obj-time');
var counts = getCount(words);
array = [];
for (let i in counts) {
  var l = i.length,
    val = counts[i];
  array.push({
    [i]: val * l
  })
}
console.log(array);
console.timeEnd('Obj-time');

最新更新