计算对象中的出现次数并记录序列中断时的数字

时间:2017-02-12 18:48:03

标签: javascript arrays

如果有人提出道歉,我已经提前道歉,我发现了类似的问题,但并不是我所需要的。

基本上我有大量的对象,简化它看起来像这样:

var objects = [
{age: '32', id: '2'},
{age: '56', id: '1'},
{age: '23', id: '2'},
{age: '45', id: '2'},
{age: '48', id: '2'},
{age: '67', id: '1'},
{age: '36', id: '2'},
{age: '45', id: '1'},
]

我需要遍历所有对象并查看id,如果id为2,我需要开始计算在序列被另一个id(示例中为1)中断之前序列中出现2次的次数。 / p>

所以在上面的例子中,结果将是:

(格式为"连续时间":"计数")
一次:2
三次:1

1 个答案:

答案 0 :(得分:1)

var objects = [
  {age: '32', id: '2'},
  {age: '56', id: '1'},
  {age: '23', id: '2'},
  {age: '45', id: '2'},
  {age: '48', id: '2'},
  {age: '67', id: '1'},
  {age: '36', id: '2'},
  {age: '45', id: '1'}
];

function getStats(arr, id) {
  var hash = {};                          // the count object
  var count = 0;                          // the counter that count how many occurences that happen after each other
  for(var i = 0; i < arr.length; i++) {   // loop through the array
    if(arr[i].id == id) {                 // if this element have the id then increment the count
      count++;
    }
    else if(count) {                      // if not, if count is bigger than 0 then increment the count inside the hash object
      hash[count] = hash[count] || 0;     // if the hash object doesn't have a counter for the current count, then create one
      hash[count]++;                      // increment that counter
      count = 0;                          // reinitialize the counter back to 0
    }
  }
  // add the last count if there is one (so if there is element at the end we won't skip them)
  if(count) {
    hash[count] = hash[count] || 0;
    hash[count]++; 
  }

  return hash;
}

console.log(getStats(objects, 2)); // you can choose any id (here it will print the result for id = 2)