Home > Software engineering >  How to count the total number of letters or characters inside of an array in Javascript
How to count the total number of letters or characters inside of an array in Javascript

Time:04-21

Part of a JavaScript program I am writing asks to count the total number of the letters from the array objects. So for example if I had an array like this.

["apple", "pear"] 

The total count of letters would be 9. I am not sure if their is a char count function in JavaScript and a lot of the examples I have seen on here only count the occurrences of individual letters. Any help with this would be appreciated.

CodePudding user response:

There are a few ways you could do this, but I think the following is a good one:

var x = ["apple", "pear"];
var result = x.map(a => a.length).reduce((a, b) => a   b);
console.log(result)

This uses the map function to turn x into an array of each item's length, in this case [5, 4]. Then sums that array using the reduce function.

CodePudding user response:

You can use forEach to get length of every element in your array, then add it to a var.

let charCount = 0;
const array = ["apple", "pear"];
array.forEach(e => {
  charCount  = e.length;
});
console.log(charCount);
  • Related