简体   繁体   English

JS包含字符串和字符串数字的数组的平均值

[英]JS Average of array containing strings and string numbers

I'm trying to get the average of an array containing strings, numbers and string numbers. 我正在尝试获取包含字符串,数字和字符串数字的数组的平均值。 The average must take into account the stringified numbers. 平均值必须考虑字符串化的数字。

I've used reduce and can get the average so far, but cannot get it to work ignoring the words. 我已经使用了reduce并可以得到到目前为止的平均值,但是却无法忽略这些单词。 This is what I have at the moment. 这就是我目前所拥有的。

           <script>

    function average() {
      const array = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9'];
      let sum = arr.reduce((x, y) =>
        typeof +x === 'Number' ? x + y : +x + y);
      sum = sum / arr.length;
      return document.write(sum);
    }
  </script>

Anyone could give me a hand? 有人可以帮我吗? Thank you. 谢谢。

Try this: 尝试这个:

a.reduce((x, y) => +y ? x + +y : x)

for the average, you need to get the total array size, which you can do it in that reduce function: 对于平均值,您需要获取数组的总大小,可以在reduce函数中实现:

let count = 0;
a.reduce((x, y) => {
    if (+y) {
        count ++;
        x += +y;
    }
    return x;
}, 0);

The second input of reduce is, as the developer on mozilla says, the initial value, which in this case we need to be 0, so all the array members get into y (if not provided, the first element would be ignored) and the count gives true result mozilla上开发人员所述, reduce的第二个输入是初始值,在这种情况下,我们需要将其设为0,这样所有数组成员都将进入y (如果未提供,则第一个元素将被忽略),并且count给出了真实的结果

UPDATE 1 If you want only the string numbers , you must use this: 更新1如果仅需要字符串号 ,则必须使用以下命令:

let sum = a.reduce((x, y) => typeof y !== 'number' && +y ? x + +y : x, 0)

and for the average, you need this : 和平均值,你需要这样的

let count = 0;
let sum = a.reduce((x, y) => {
    if (typeof y !== 'number' && +y) {
        x + +y;
        count ++;
    }
    return x;
}, 0);
let average = sum / count;

This works exactly as you expected. 这完全符合您的预期。

You could filter and map the numbers to number, while respecting zero values as well and then add all values and divide by the length of the number count. 您可以过滤数字并将其映射为数字,同时也要遵守零值,然后将所有值相加并除以数字计数的长度。

 const not = f => (...a) => !f(...a), add = (a, b) => a + b, array = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9', '1a'], temp = array.filter(not(isNaN)).map(Number), avg = temp.reduce(add) / temp.length; console.log(avg); 

Assuming you only want average of actual numeric values filter out the non numeric strings and reduce the others 假设您只希望将实际数值的平均值过滤掉非数字字符串并减少其他字符串

 const arr = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9']; const nums = arr.filter(n => !isNaN(n)).map(Number) const ave = nums.reduce((x, y) => x + y) / (nums.length || 1); console.log(ave) 

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

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