Javascript计算重复项和唯一性并添加到数组中 [英] Javascript count duplicates and uniques and add to array
本文介绍了Javascript计算重复项和唯一性并添加到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试计算日期数组中的重复项,并将其添加到新数组中.
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.
我想要的是:
[a, a, b, c, c]
=> [a: 2, b: 1, c: 2]
代码:
$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]];}
}
有什么建议吗?
推荐答案
为此,您可能需要一个对象,而不是数组.因此,您的工作已经很不错了,但是if
的条件搞砸了:
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]];
}
代码段
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);
或者以更好的方式,您可以像其他人一样使用.reduce
.一个简单的reduce
函数将是:
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);
这篇关于Javascript计算重复项和唯一性并添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文