Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

305
Vistas
How to get the number nearest to the average of array of numbers? JavaScript

If I have an array of numbers and I want get the number nearest to average, how can I get that number?

I've tried to sort the array in an ascending order, followed by retrieving the middle element which is the average.

Note: I used Math.floor() in case if the length of the array is odd not even number

const arr = [1, 6, 10, 3, 15, 9, 4, 7];
const arrSorted = arr.sort((a,b)=>a-b);
const nearToAVG = arrSorted[Math.floor(arr.length/2)];
console.log(nearToAVG); // 7

Are there any better ways of getting the number near to the average in array?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Let's dissect this problem. You want the index with the nearest value to the average of the the array indices. To get that you may first calculate the sum of the array. Knowing the sum, you can do a second sweep of the array arr to take the difference of each element from the average and store it in a variable. Lastly, you would update that variable if the difference between the average and the current index is closer to zero than the stored value. By the end of the array, you will have the answer you are looking for.

Here is a simple example of the above:

const arr = [1, 6, 10, 3, 15, 9, 4, 7];

// get average
let sum = 0;
for(let i = 0; i < arr.length; sum += arr[i], i++);
let ave = sum / arr.length; // 6.875


function nearestIdxToAverage(array, average) {
    if(!array.length) return 0;

    // stores initial difference and gets replaced by index
    let nearest = Math.abs(array[0] - average);

    for(let i = 0; i < array.length; i++) {
        const diff = Math.abs(array[i] - average);
        // stores the offset of the diff closest to 0 (relative to the average)
        nearest = (diff < nearest)? i: nearest;
    }

    return nearest;
}

console.log(`average: ${ave}\nnearest idx: ${nearestIdxToAverage(arr, ave)}`);

// average: 6.875
// nearest idx: 7
about 4 years ago · Juan Pablo Isaza Denunciar

0

As I noted in a comment to another answer, this is one of those cases, when you really need to be more precise than "average". The median and the mean are the most common averages, and depending on which you want, you may get different answers. For instance, in [3, 20, 1, 4, 2], the median is 3, but, since the mean is 6, the original value closest to the mean is 4.

This version assumes you want to get the value in the array closest to the arithmetic mean of the numbers:

const closestToMean = (ns, m = ns .reduce ((a, b) => a + b, 0) / ns .length) =>
  ns .reduce ((c, n) => Math .abs (n - m) < Math .abs (c - m) ? n : c, Infinity)

console .log (closestToMean ([3, 20, 1, 4, 2]))
console .log (closestToMean ([1, 6, 10, 3, 15, 9, 4, 7]))

We sum the numbers and divide by their length to find the mean, then we fold the list of numbers, keeping at every stage the one closer to that mean.

I would actually prefer to break this up and extract the common helper functions sum, which totals an array of numbers, mean, which uses sum to calculate the arithmetic mean, and minimumBy, which finds the smallest element of an array, according to the result of applying the function supplied to each element. I think this version is much more readable:

const sum = (ns) =>
  ns .reduce ((a, b) => a + b, 0)

const mean = (ns) => 
  sum (ns) / ns .length

const minimumBy = (fn) => (ns) =>
  ns .reduce ((c, n) => fn (n) < fn (c) ? n : c, Infinity)

const closestToMean = (ns, m = mean (ns)) =>
  minimumBy (n => Math .abs (n - m)) (ns)

console .log (closestToMean ([3, 20, 1, 4, 2]))
console .log (closestToMean ([1, 6, 10, 3, 15, 9, 4, 7]))

... and we've also happened upon some useful functions to use elsewhere in this program or others.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another approach to achieve that By using:

  • reduce to accumulate the sum and divide it by its length to get the average.

  • map iterate over that array and return each number with its nearByAVG (distance between that number and average).

  • sort by that property in order ascending and get the first one that has the minimum distance to average.

const arr = [1, 6, 10, 3, 15, 9, 4, 7];
const sum = arr.reduce((acc, curr)=>acc+curr);
const avg = sum/arr.length;
const arrMaped = arr.map(num=>({num,nearByAVG: Math.abs(num-avg)}));
const arrSorted = arrMaped.sort((a,b)=>a.nearByAVG-b.nearByAVG);
console.log(arrSorted[0].num)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda