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!

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". Commented Dec 15, 2019 at 19:15
  • 1
    JSYK, you should avoid document.write: stackoverflow.com/questions/802854/… Commented Dec 15, 2019 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. Commented Dec 15, 2019 at 19:26

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Resisting the urge to make one liners, and caching the average, would make this considerably better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.