Javascript Array Question 26

Introduction

Max, Min, Average

Given an array, create a new array with max, min, and average values.

function max_min_avg(arr) {
  var max = arr[0];
  var min = arr[0];
  var sum = arr[0];
  var avg, new_arr;
  //your code
  return new_arr;
}
max_min_avg([1,2,3,4]);



function max_min_avg(arr) {
  var max = arr[0];
  var min = arr[0];
  var sum = arr[0];
  var avg, new_arr;
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
    if (arr[i] < min) {
      min = arr[i];
    }
    sum += arr[i];
  }
  avg = sum / arr.length;
  new_arr = [max, min, avg];
  return new_arr;
}
max_min_avg([1,2,3,4]);



PreviousNext

Related