Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Arrays Javascript

Tags:

javascript

I am brand new to javascript(I have been exposed to DOM manipulation, however for this assignment we can display input in a simple console.log according to the prof) and I have came across this problem that was due for a school assignment, I need to take user input of 3 numbers, display them, and show the max and min number entered, as well as the average. The code I have below preforms as I intended but what I am looking for is feedback for improvements, I am still in the process of training my brain to break down these types of problems as well as organize my thinking. I would like to be practicing the "best" methods or most effective methods, as my thinking and logic is not yet defined and I am in the stage where everything is new so I may as learn the most effective ways/strategies. Any improvements or better ways to solve this question is greatly appreciated.

Thanks!

let num = parseFloat(prompt("enter your first number"));
let num1 = parseFloat(prompt("enter your second number"));
let num2 = parseFloat(prompt("enter your third number"));

let avg = parseFloat(console.log('The Average of The Numbers',
  num, ',', num1, ',', num2, 'Is:', (num + num1 + num2) / 3));

let numTot = parseFloat(console.log(`The Numbers You Have Entered 
  Are`, num, +num1, +num2));

let total = parseFloat(console.log('The Total Of', num, '+', num1,
  '+', num2, 'Is :', num + num1 + num2));

let highest = Math.max(num, num1, num2);
let lowest = Math.min(num, num1, num2);

console.log("The Highest Number Entered Is:", highest);
console.log("The Lowest Number Entered Is:", lowest);
like image 791
hazey Avatar asked Jan 25 '19 02:01

hazey


2 Answers

Here's how I would do it:

  • Declare your numbers in an array. Prefix them with + to coerce them from a String to Number.
  • Array.reduce to loop over your array and calculate the average.
  • Use spread syntax to obtain min/max values in the accumulator object, you pass to .reduce.

// prompt returns a String, prefix with + 
// to coerce them to Numbers, since we'll be 
// working with numbers.
const numbers = [
  +prompt('Enter number 1'),
  +prompt('Enter number 2'),
  +prompt('Enter number 3')
]

const result = numbers.reduce((acc, number, index) => {
  // For each number:
  
  // Add the number to the accumulator sum.
  acc.sum += number
 
  // If this is the last iteration:
  if (index === numbers.length - 1) {
    // Calculate the average from the sum.
    acc.avg = acc.sum / numbers.length
    
    // Also discard the sum property, we no longer need it.
    delete acc.sum
  }
  
  // Return the accumulator for the next iteration.
  return acc
}, {
  // Our accumulator object, initialised with min/max values.
  min: Math.min(...numbers),
  max: Math.max(...numbers),
  sum: 0,
  avg: 0
})
 
// Log the processed accumulator.
console.log(result)

Why use a loop at all?

Array.reduce loops over an array, similarly to how a for loop does. Using a loop-like construct allows you to add more numbers in the numbers array without needing to modify your calculations code.

Why divide at the end of the loop?

Summing the numbers and dividing once at the end of the loop helps avoid numerical errors.

If you do acc.avg = acc.avg + number / numbers.length on each iteration you'll start noticing that the average turns out to be a bit off. Try it just for the sake of it.

Might look a bit complex for a beginner but those 2 concepts (esp. Array.reduce) are worth looking into. FWIW, the classroom example given for teaching Array.reduce is calculating averages from an array of numbers.

like image 96
nicholaswmin Avatar answered Oct 12 '22 01:10

nicholaswmin


If you want to use advances features, then reference to the Nik Kyriakides answer. On this approach I will use a for loop to ask for numbers in an iterative way and calculate the minimun, maximun and total progressively. The average could be obtained dividing total by the quantity of numbers you asked for:

const numbersToAsk = 3;
let max, min, avg, total = 0;

for (var i = 1; i <= numbersToAsk; i++)
{
    // Ask the user for a new number and get it.
    let num = parseFloat(prompt("enter your number " + i));

    // Sum the new number to the previous accumulated total.
    total += num;

    // Recalculate the new maximum, if there wasn't a previous one,
    // just assign the current number.
    max = !max ? num : Math.max(max, num);

    // Recalculate the new minimum, if there wasn't a previous one,
    // just assign the current number.
    min = !min ? num : Math.min(min, num);
}

// Calulate the average.
avg = total / numbersToAsk;

// Show the obtained results on the console.
console.log(
    "Total: " + total,
    "Average: " + avg,
    "Min: " + min,
    "Max: " + max
);
like image 44
Shidersz Avatar answered Oct 12 '22 02:10

Shidersz