Topic Overview and Importance

Hello and welcome! Today, we're exploring practical data manipulation techniques in JavaScript. We'll use JavaScript arrays to represent our data stream and perform projection, filtering, and aggregation. And here's the star of the show: our operations will be neatly packaged within a JavaScript class! No mess, all clean code.

Introduction to Data Manipulation

Data manipulation is akin to being a sculptor but for data. We chisel and shape our data to get the desired structure. JavaScript arrays are perfect for this, and our operations will be conveniently bundled inside a JavaScript class. So, let's get our toolbox ready! Here's a simple JavaScript class, DataStream, that will serve as our toolbox:

class DataStream {
    constructor(data) {
        this.data = data;
    }
}
Data Projection in Practice

Our first stop is data projection. Think of it like capturing a photo of our desired features. Suppose we have data about people. If we're only interested in names and ages, we project our data to include just these details. We'll extend our DataStream class with a projectData method for this:

class DataStream {
    constructor(data) {
        this.data = data;
    }

    projectData(keys) {
        const projectedData = this.data.map(d => {
            let newObj = {};
            keys.forEach(key => {
                newObj[key] = d[key] !== undefined ? d[key] : null;
            });
            return newObj;
        });
        return projectedData;
    }
}

// Let's use it!
const ds = new DataStream([
    { 'name': 'Alice', 'age': 25, 'profession': 'Engineer' },
    { 'name': 'Bob', 'age': 30, 'profession': 'Doctor' },
]);

const projectedDs = ds.projectData(['name', 'age']);
console.log(projectedDs);  // Outputs: [{ 'name': 'Alice', 'age': 25 }, { 'name': 'Bob', 'age': 30 }]

As you can see, we now have a new array with just the names and ages!

Data Filtering in Practice

Next, we have data filtering, which is like cherry-picking our preferred data entries. We'll extend our DataStream class with a filterData method that uses a "test" function to filter data:

class DataStream {
    constructor(data) {
        this.data = data;
    }

    // ... other methods ...

    filterData(testFunc) {
        const filteredData = this.data.filter(testFunc);
        return filteredData;
    }
}

// Applying it:
const ds = new DataStream([
    { 'name': 'Alice', 'age': 25, 'profession': 'Engineer' },
    { 'name': 'Bob', 'age': 30, 'profession': 'Doctor' },
]);

const ageTest = x => x['age'] > 26;  // our "test" function
const filteredDs = ds.filterData(ageTest);
console.log(filteredDs);  // Outputs: [{ 'name': 'Bob', 'age': 30, 'profession': 'Doctor' }]

With the filter method, our output is an array with only Bob’s data, as he's the only one who passes the 'age over 26' test.

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