Javascript count duplicates and uniques and add to array

前端 未结 5 1514
无人及你
无人及你 2021-01-26 10:29

I\'m trying to count duplicates in an array of dates and add them to a new array.

But i\'m only getting the duplicates and the amount of times they exist in the array. <

5条回答
  •  被撕碎了的回忆
    2021-01-26 10:57

    You might need an object for this, not an array. So what you are doing is already great, but the if condition is messing up:

    $scope.result = {};
    for (var i = 0; i < $scope.loginArray.length; ++i) {
      if (!$scope.result[$scope.loginArray[i]])
        $scope.result[$scope.loginArray[i]] = 0;
      ++$scope.result[$scope.loginArray[i]];
    }
    

    Snippet

    var a = ['a', 'a', 'b', 'c', 'c'];
    var r = {};
    for (var i = 0; i < a.length; ++i) {
      if (!r[a[i]])
        r[a[i]] = 0;
      ++r[a[i]];
    }
    console.log(r);

    Or in better way, you can use .reduce like how others have given. A simple reduce function will be:

    var a = ['a', 'a', 'b', 'c', 'c'];
    var r = a.reduce(function(c, e) {
      c[e] = (c[e] || 0) + 1;
      return c;
    }, {});
    
    console.log(r);

提交回复
热议问题