1

I'm trying to get all the numbers that are higher than the average of a given Array. (this goes into an HTML page so it's with document.write this is what I wrote:

sumAndBigger(arrayMaker());

function sumAndBigger(array) {
  for (i = 0; i < array.length; i++) {
    sum += array;
  }
  var equalAndBigger = []
  var avg = sum / array.length;
  for (i = 0; i < array.length; i++) {
    if (array[i] > avg) {
      equalAndBigger.push(array[i])
    }
  }
  document.write('The numbers are: ' + equalAndBigger)
}

function arrayMaker() {
  var array = [];
  for (i = 0; i < 5; i++) {
    var entrie = +prompt('Enter a number: ');
    array.push(entrie)
  }
  return array;
}

This doesn't seem to work.. what am I doing wrong here?

Thanks in advance!

6502
  • 104,192
  • 14
  • 145
  • 251
Eden Hazani
  • 25
  • 1
  • 3
  • 2
    `sum += array;` wat? `sum` isn't declared, and adding the array object makes no sense to me. You probably meant to declare `sum` before the loop, and use `sum += array[i];`. Also, the singular of "entries" is "entry". – ASDFGerte Dec 15 '19 at 19:15
  • 1
    JSYK, you should avoid document.write: https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – iPhoenix Dec 15 '19 at 19:16
  • PS: you also never declare `i` in any of your loops. This only works in non-strict, and is not a good habit to pick up. – ASDFGerte Dec 15 '19 at 19:26

1 Answers1

2

Ok so here I am giving you a one-liner code to get all the elements from the array that are "strictly greater than" the average value

let array = [1, 2, 3, 4, 5]
let allNums = array.filter(v => v > array.reduce((x, y) => x + y) / array.length);

Explanation

  • array.reduce((x, y) => x + y) → sum of all elements in the array
  • array.reduce((x, y) => x + y) / array.length → getting the average

Output

[4, 5]

MORE DETAILED CODE

function getAverage(arr) {
  let sum = 0;

  for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  return sum / arr.length;
}

function getGreaterThanAverage(arr) {
  let avg = getAverage(arr);
  let numbers = [];

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > avg) {
      numbers.push(arr[i]);
    }
  }

  return numbers;
}
tbhaxor
  • 953
  • 2
  • 7
  • 28