"price" is an array of 6 prices. I want to find the sum and average and the highest and lowest price in that array. Currently my answer2 only displays the numbers on a straight line.
let answer2 = ""
for (let k=0; k < price.length; k ) {
answer2 = price[k];
}```
CodePudding user response:
You could always take advantages of the Arrays reduce method of EcmaScript, take a look at this snippet of code using that method with your case. Hope this helps buddy, cheers!
// The array with the prices you mentioned but didn't include on the code
const price = [23,45,12,67,89,87];
// Let's calculate the sum of all array elements first
const sum = price.reduce((acc,i)=>acc i,0);
// we print this and use the array length property to calculate average
console.log(`Sum: ${sum} Average: ${(sum/price.length).toFixed(2)}`);
CodePudding user response:
You can create a simple for loop to get (Sum, Avg, Max, and Min) from the array.
let price=[23,88,45,66,3,10,2];
let result={"sum":0,"avg":0,"max":0,"min":0}
let size = arr.length;
for(let i=0;i<size;i ){
if(arr[i]>result.max){
result.max=arr[i];
}
if(i==0 || arr[i]<result.min){
result.min=arr[i]
}
result.sum =arr[i]
}
result.avg=Number((result.sum/size).toFixed(2));
console.log(result)