简体   繁体   English

查找数组中字符串的平均字符串长度-Javascript

[英]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. 您可以reduce字符串数组。 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: 您可以使用Array.prototype.reduce汇总所有引号的总长度,然后将它们除以引号数组的长度/大小:

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 : 您也可以.reduce与以下内容一起使用:

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. 您可以在每个元素上使用forEach而不创建新的数组。 May be long but readable: 可能很长,但可读性:

https://jsfiddle.net/p19qbodw/ - run this in an opened console to see the result https://jsfiddle.net/p19qbodw/-在打开的控制台中运行此命令以查看结果

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. 将所有数组值连接到单个String,然后可以计算平均长度。

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

console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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