js数组获取相同元素个数,归档排序

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <script>
  var arr = [];
  var result = ['2017年6月', '2017年6月', '2017年6月', '2017年5月', '2017年5月', '2017年7月', '2017年7月']
  result.sort()
  for (var i = 0; i < result.length;) {
    var count = 0;
    for (var j = i; j < result.length; j++) {
      if (result[i] === result[j]) {
        count++;
      }
    }
    arr.push({
      date: result[i],
      count: count
    })
    i+=count;
  }

  for (var k = 0; k < arr.length; k++) {
    console.log(arr[k])
  }
  </script>
</body>

</html>

结果:

可以用来做归档统计

原文地址:https://www.cnblogs.com/yesyes/p/7059257.html