0

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.

1
  • I you only need to count the number of character occurrences, You could also use a map/dictionary that maps a character to its frequency. Commented Apr 7, 2017 at 12:54

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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")
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.