An array of values. looping many times to calculate mean, closest matching array value, and then finding its index
You can remove the last line searching for the index since you can get the index in the reduce method.

Btw, you forgot to add Math.abs to deal with positive value when comparing.

Demo:



const cols = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

const mean = cols.reduce((prev, curr) =&gt; prev + curr, 0) / cols.length;

const { value, index } = cols.reduce((prev, curr, i) =&gt; {
    // You have deal in absolute 
    if (Math.abs(curr - mean) &lt; Math.abs(prev.value - mean)) {
        return { value: curr, index: i }
    } else {
        return prev
    }
}, { value: cols[0], index: 0 });

console.log({ mean, value, index })