Data Aggregation Techniques in TypeScript

Introduction to Data Aggregation Methods in TypeScript

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 TypeScript. 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: number[] = [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? TypeScript's type annotations, combined with methods like length, reduce, Math.min, and Math.max, have our answers:

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

// Use reduce and length to find the average age
const averageAge: number = totalAges / numPeople; // Result: 23

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

In this code snippet, we utilize several built-in functions for basic aggregation tasks. The length property is used to count the number of elements in the ages array, giving us the total number of people. The reduce function used here to sum the ages, will be discussed in detail later in this lesson. For now, it is important to note that reduce accumulates elements of an array into a single value. Next, Math.min and Math.max help determine the youngest and oldest ages by finding the minimum and maximum values in the array, respectively. Finally, the average age is calculated by dividing the total age by the number of people, and the age range is obtained by subtracting the youngest age from the oldest age. These operations, along with TypeScript’s type annotations, ensure both code clarity and type safety.

Advanced Aggregation using For and While Loops

For deeper analysis, such as finding the mode or most frequent age, we can use for and while loops effectively:

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

// Initialize a Map to store the frequency of each age
const frequencies = new Map<number, number>();

// Use a for loop to populate frequencies
for (const age of ages) {
    frequencies.set(age, (frequencies.get(age) || 0) + 1);
}

// Find the age with the max frequency
let maxFreq: number = 0;
let modeAge: number = -1;
for (const [age, freq] of frequencies) {
    if (freq > maxFreq) {
        maxFreq = freq;
        modeAge = age;
    }
}

console.log('Max frequency:', maxFreq); // Max frequency: 4
console.log('Mode age:', modeAge); // Mode age: 22

The code calculates the mode (the most frequent age) from an array of ages.

The line frequencies.set(age, (frequencies.get(age) || 0) + 1); updates the frequency of each age in the frequencies Map. Here’s a breakdown:

  • frequencies.get(age) retrieves the current frequency of the age from the Map.
  • If the age is not found (i.e., frequencies.get(age) is undefined), the expression (frequencies.get(age) || 0) ensures it starts at 0.
  • Then, + 1 increments the frequency by 1 for each occurrence of the age.
  • Finally, frequencies.set(age, ...) updates the Map with the new frequency.

The rest of the code finds the age with the highest frequency (mode) by iterating through the Map.

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