An array of values. looping many times to calculate mean, closest matching array value, and then finding its index I have an array of values. (cols)

I want to find out which index of cols contains the value closest to the mean of cols.

Can I combine these functions so that I'm not repeating loops?

let mean = cols.reduce((prev, curr) =&gt; prev + curr) / cols.length;
let closest = cols.reduce((prev, curr) =&gt; (curr - mean) &lt; (prev - mean) ? curr : prev);
let meanCol = cols.indexOf(closest);
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 })