[英]Im trying to filter then sort an array of numbers and string but my code isn't working
[英]im trying to find an average of some numbers in my array but not all of them
好吧,我一直在环顾四周,但我试图找到一组超过 1000 的数字的平均值并让它忽略其他所有内容。 这就是我所拥有的,但我不确定如何启动代码本身。 我确实知道要找到所有内容的平均值,您需要将总和除以长度。 但我希望它忽略 1000 以下的任何内容。在此先感谢。
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title></title>
<script>
/*
defining table
<input: none
processing: get the last element in each array
output: the last element in the arrays
*/
function averageBig(list){
// this is the list of arrays needed
var list1=[70, 1010, 950,2014,6];
var list2 = [ -72.3, 3000, 873, 2312, 68, 7501.3]
var list3 = [ 70, 950, 671, 6 ]
// this should test my avg function by calling it three times
var avg1 = average(list1);
var avg2 = average(list2);
var avg3 = average(list3);
// output the answers
var output = avg1 + '<br>' +
avg2 + '<br>' +
avg3
document.getElementById('outputdiv').innerHTML = output;
}
function average(list)
var avg = ()
</script>
</head>
<body>
<button type="button" onclick="averageBig()">test me </button>
<div id="outputdiv"></div>
</body>
</html>
任何帮助表示赞赏。
因此,首先您需要过滤每个列表以获得超过 1000 个的数字 - 然后您需要对符合该标准的结果数字进行平均。
请注意,将每个列表传递给平均值 function - 第一步是过滤该值 - 然后使用过滤后的数组 - 计算平均值。 平均数字的传统方法是遍历数组 - 将数字相加,然后除以项目数。
较新的方法是使用 reduce() 方法,它允许在一行中实现相同的功能。 另外——注意 reduce 方法末尾的0
它作为 reduce 方法第一次迭代的起始数字。
不确定这是否是故意的 - 但第三个数组/列表没有任何符合大于 1000 标准的数字 - 所以 reduce 方法返回 NaN 并且 function 必须适应 -i 正在处理它返回一个字符串来表示问题是什么。
另外 - 您可以扩展它以将需要超过的数字作为参数包含到 function 中。
function averageBig(){ // this is the list of arrays needed let list1=[70, 1010, 950,2014,6]; let list2 = [ -72.3, 3000, 873, 2312, 68, 7501.3]; let list3 = [ 70, 950, 671, 6 ] // this should test my avg function by calling it three times var avg1 = average(list1); var avg2 = average(list2); var avg3 = average(list3); // output the answers var output = avg1 + '<br/>' + avg2 + '<br/>' + avg3 document.getElementById('outputdiv').innerHTML = output; } function average(arr) { // step 1 - filter the incoming list to match the criterion let numArr = arr.filter(num => num > 1000); // step 2 calculate the average of the array values let ave = Math.round(numArr.reduce((a, b) => (a + b), 0) / numArr.length); // step 3 - accomodate the issue of not having a valid result if(isNaN(ave)) {ave = 'No average possible'} // step 4 return the result (either the rounded average - or the explanatory string) return ave }
<button type="button" onclick="averageBig()">test me </button> <div id="outputdiv"></div>
只需使用您的average()
方法对 1000 以上的数字求和。最后将其除以 1000 以上的数字总数。这是一个简单的方法:
function average(list){
var sum=0, length=0;
for(element of list)
{
if (element > 1000)
{
sum+=element;
length++;
}
}
return isNaN(sum/length) ? 'No result' : sum/length
}
注意:您也可以使用过滤器和减少作为@gavgrif 的答案。 我只是以最简单的方式回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.