Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,821 answers

573 users

How to calculate the mean and the standard deviation of an array of floating-point values in Node.js

1 Answer

0 votes
function calculateMean(data) {
    if (data.length === 0) return 0.0;

    const sum = data.reduce((acc, val) => acc + val, 0);
    
    return sum / data.length;
}

function calculateStandardDeviation(data, mean) {
    if (data.length < 2) return 0.0;

    const sumOfSquaredDiffs = data.reduce((acc, val) => {
        const diff = val - mean;
        return acc + diff * diff;
    }, 0);

    const variance = sumOfSquaredDiffs / (data.length - 1); 
    
    return Math.sqrt(variance);
}

const numbers = [3.4, 2.8, 7.3, 5.0, 6.2];
const mean = calculateMean(numbers);
const stddev = calculateStandardDeviation(numbers, mean);

console.log(`Mean: ${mean.toFixed(2)}`);
console.log(`Standard Deviation: ${stddev.toFixed(2)}`);



/*
run:

Mean: 4.94
Standard Deviation: 1.88

*/

 



answered Jun 29, 2025 by avibootz
...