gpt4 book ai didi

angularjs - 在 ng-repeat 中显示具有重复出现次数的唯一项目

转载 作者:行者123 更新时间:2023-12-01 09:50:01 25 4
gpt4 key购买 nike

我有以下 JSON:

[{"brand":"abc"},{"brand":"xyz"},{"brand":"abc"},{"brand":"abc"},{"brand":"por"},{"brand":"xyz"}]

使用ng-repeat,我如何显示 -

Brand Occurances
abc (3)
xyz (2)
por (1)

即品牌名称(同一品牌名称重复出现的次数)?

最佳答案

您可以创建一个自定义函数,该函数将从现有数组中返回带有 repeatvie 值(出现次数)的计数

与过滤器一起显示来自 JSON 的唯一值:

$scope.getCount = function(i) {
var iCount = iCount || 0;
for (var j = 0; j < $scope.brands.length; j++) {
if ($scope.brands[j].brand == i) {
iCount++;
}
}
return iCount;
}

过滤器看起来像这样:

app.filter('unique', function() {

return function (arr, field) {
var o = {}, i, l = arr.length, r = [];
for(i=0; i<l;i+=1) {
o[arr[i][field]] = arr[i];
}
for(i in o) {
r.push(o[i]);
}
return r;
};
})

Working Plunkr

关于angularjs - 在 ng-repeat 中显示具有重复出现次数的唯一项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39382834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com