0

"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];

    }```
coder598
  • 1
  • 1
  • 3
    Does this answer your question? [How to compute the sum and average of elements in an array?](https://stackoverflow.com/questions/10359907/how-to-compute-the-sum-and-average-of-elements-in-an-array) – Mister Jojo Oct 08 '22 at 00:42

2 Answers2

0

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)}`);
Alvison Hunter
  • 620
  • 5
  • 13
  • Hi Alvison How would I use that reduce method using my for loop? – coder598 Oct 08 '22 at 00:35
  • The reduce itself does the iteration of your array elements, hence you don't need a separated for loop to calculate this sum. You se,, the reduce will accumulate your sum in every iteration so the result in the sum of all these elements and for the average, you simply divide that sum per de amount of elements on the array. I left a link to the reduce documentation in the above code example. – Alvison Hunter Oct 08 '22 at 01:46
0

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 = price.length;
for(let i=0;i<size;i++){
    if(price[i]>result.max){
        result.max=price[i];
    }
    if(i==0 || price[i]<result.min){
        result.min=price[i]
    }
    result.sum+=price[i]
}
result.avg=Number((result.sum/size).toFixed(2));
console.log(result)
Jitendra Pathak
  • 299
  • 1
  • 10