Introduction to Data Aggregation Methods

Welcome to today's lesson! Our topic for the day is data aggregation, a crucial aspect of data analysis. Like summarizing a massive book into key points, data aggregation summarizes large amounts of data into important highlights.

By the end of this lesson, you'll be equipped with several aggregation methods to summarize data streams in JavaScript. Let's get started!

Basic Aggregation using Built-in Functions

Let's say we have an array of numbers denoting the ages of a group of people:

const ages = [21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22];

Common questions we might ask are: How many people are in the group? What's their total age? Who's the youngest and the oldest? JavaScript's handy built-in properties and functions like length, reduce, Math.min, and Math.max have our answers:

const numPeople = ages.length; // Number of people (12)
const totalAges = ages.reduce((a, b) => a + b, 0); // Total age (276)
const youngestAge = Math.min(...ages); // Youngest age (20)
const oldestAge = Math.max(...ages); // Oldest age (27)

// Use reduce and length to find the average age
const averageAge = ages.reduce((a, b) => a + b, 0) / ages.length; // Result: 23

// Use Math.max() and Math.min() to find the range of ages
const ageRange = Math.max(...ages) - Math.min(...ages); // Result: 7

These functions provide essential aggregation operations and are widely used with data streams.

Advanced Aggregation using For and While Loops

For deeper analysis, such as calculating the average age or range of ages, we resort to for and while loops.

For example, using for loops, we can also find the mode or most frequent age:

const ages = [21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22];

// Initialize an object to store the frequency of each age
const frequencies = {};

// Use a for loop to populate frequencies
for (const age of ages) {
    if (!frequencies[age]) {
        frequencies[age] = 0;
    }
    frequencies[age] += 1;
}

// Find the age with a max frequency
let maxFreq = 0;
let modeAge = -1;
for (const age in frequencies) {
    if (frequencies[age] > maxFreq) {
        maxFreq = frequencies[age];
        modeAge = age;
    }
}
console.log('Max frequency:', maxFreq); // Max frequency: 4
console.log('Mode age:', modeAge); // Mode age: 22

While loops can also be used similarly for complex tasks.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal