简体   繁体   中英

Finding Average String Length of Strings in Array - Javascript

I have an array of six quotes and I'm trying to find the average length of each quote. I'm thinking I need to create a new array of the string lengths, then average. But I can't figure out how to get the counts of the original array into the new array. How do I get the counts of the first array into the new array?

 arr = [1, 12, 123, 1234] // works with numbers too avg = arr.join('').length / arr.length // 10 / 4 = 2.5 console.log(avg) 

You can reduce your array of strings. For example:

['a', 'bb', 'ccc', 'dddd']
  .reduce((a, b, i, arr) => a + b.length / arr.length, 0)

You can use Array.prototype.reduce to sum up the total length of all quotes and them divide it by the length/size of the quotes array:

const quotes = [
    "Quote #1",
    "Longer quote",
    "Something...",
    ...
];

// Sum up all the quotes lengths
const totalQuotesLength = quotes.reduce(function (sum, quote) {
    return sum + quote.length;
}, 0);

// Calculate avg length of the quotes
const avgQuoteLength = (
    totalQuotesLength / quotes.length
);

If I understood right, you want to find the average length of strings in an array, you can do it like this:

var total = 0;
for(var i = 0; i < array.length; i++){
    total+=array[i].length;
}
var average = total/array.length;

You can simply use also .reduce with something like :

const numbers = [1,2,3,4,5,6];
const total = numbers.reduce((acc, value) => acc + value, 0);
const average = total / numbers.length;

I hoe it will help !

You could use forEach on each element without creating new arrays. May be long but readable:

https://jsfiddle.net/p19qbodw/ - run this in an opened console to see the result

var quotes = ["quotequote", "quote", "qu"]
charsSum = 0,
avarage;

quotes.forEach( (el) => {
charsSum += el.length;
});

 avarage = charsSum/quotes.length;

Join all array values to a single String and then you can calculate the average length.

var yourArray = ["test", "tes", "test"],
    arrayLength = yourArray.length,
    joined = yourArray.join(''),
    result = joined.length / arrayLength;

console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM