Reputation: 245
I have array like this
vm.name =['A','A','B','B','C','C','C'];
I do like this to count item
vm.a =[];
vm.b=[];
vm.c=[];
for(var i =0;i<vm.name.length;i++){
if(vm.name[i] ==='A'){
vm.a.push(vm.name[i])
}
if(vm.name[i] ==='B'){
vm.b.push(vm.name[i])
}
if(vm.name[i] ==='C'){
vm.c.push(vm.name[i])
}
}
and render in HTML
{{vm.a.length}} //2
{{vm.b.length}} //2
{{vm.c.length}} //3
But I don't think it is good. If you have a better way, please tell me.
Upvotes: 0
Views: 59
Reputation: 7911
You can create these arrays dynamically using this beautiful function called reduce
:)
vm.name = ['A', 'A', 'B', 'B', 'C', 'C', 'C'];
vm = vm.name.reduce(function(obj, cur) {
obj[cur.toLowerCase()] = obj[cur.toLowerCase()] || []
obj[cur.toLowerCase()].push(cur)
return obj;
}, vm)
console.log(vm.b.length)
console.log(vm.c.length)
Upvotes: 4
Reputation: 41455
It is better to use switch
instead of if
conditions in a scenario like this.
for (var i = 0; i < vm.name.length; i++) {
switch (vm.name[i]) {
case "A":
vm.a.push(vm.name[i])
break;
case "B":
vm.b.push(vm.name[i])
break;
case "C":
vm.c.push(vm.name[i])
break;
default:
console.log("no such type")
}
}
Upvotes: 1