锯齿状阵列中的平均数

时间:2017-12-15 11:34:34

标签: javascript arrays loops average jagged-arrays

我制作了一个看起来像这样的锯齿状阵列:

我试图弄清楚如何计算每一行的平均数。有什么建议吗?

这里是完整的代码:

    var tempen = [
    [" ","00-08","08-16","16-24","Medel"],
    ["Malmö","12","16","9"," "],
    ["Mariestad","13","15","10"," "],
    ["Stockholm","13","15","13"," "],
    ["Göteborg","13","14","12"," "]
    ];
    function printit()
    {
    var varMyinnerHTML = "<table border='1'>";

    for (i=0;i<tempen.length;i++)
    {
    varMyinnerHTML +="<tr>";
        for (j=0;j<tempen[i].length;j++)
        {
        varMyinnerHTML +="<td>"+ tempen[i][j] +"</td>";
        }
    varMyinnerHTML +="</tr>";
    }
    varMyinnerHTML +="</table>";
    document.getElementById("kontainer").innerHTML=varMyinnerHTML;
    }
    </script>
    </head>
    <body>
    <h1>Uppgift 1</h1>
    <form name="f1">
        <input type="button" value="print" onclick="printit()"/>
        </form>
        <div id="kontainer"/>
        </body>
</html>

1 个答案:

答案 0 :(得分:0)

const sum = (nos)=> nos.reduce((p,c)=> p + (+c), 0);
const avg = (nos)=> sum(nos) / nos.length;
const tail = ([_, ...tail])=> tail; 
const averages = (arr) => arr.map((i) => avg(tail(i)));

var myArray = [["Help", "12", "16", "9", " "], ["Me", "13", "15", "10", " "], ["Please", "13", "15", "13", " "], ["Sir", "13", "14", "12", " "]];
console.log(averages(myArray));

或者,如果添加了composition operator

const averages = (arr)=> arr.map(tail :> avg);