Introduction to Data Projection Techniques

Welcome! Today, we'll delve into Data Projection Techniques in JavaScript! Data projection is akin to using a special light to make diamonds shine brighter amidst other gems, aiding their identification.

This lesson will illuminate the concept of data projection, its implementation using JavaScript’s Array.prototype.map() method, and how to integrate it with filtering. Let's forge ahead!

Implementing Data Projection in JavaScript

Data projection involves applying a function to a data stream's elements, resulting in a reshaped view. A common instance of data projection is selecting specific fields from databases.

Data projection in JavaScript employs the Array.prototype.map() method. Here's an illustration of finding each number's square in a list of numbers:

const numbers = [1, 2, 3, 4, 5];  // our data stream

function square(n) {
    return n * n;  // function to get a number's square
}

// map applies the square function to each number in the list
const squaredNumbers = numbers.map(square);

console.log(squaredNumbers);  // prints: [1, 4, 9, 16, 25]
Data Projection in JavaScript: Advanced Topics

For complex operations on data streams, JavaScript employs arrow functions (anonymous functions). Let's convert a list of sentences to lowercase:

const sentences = ["HELLO WORLD", "JAVASCRIPT IS FUN", "I LIKE PROGRAMMING"];  // our data stream

// map applies the arrow function to each sentence in the list
const lowerSentences = sentences.map(sentence => sentence.toLowerCase());

console.log(lowerSentences);  // prints: ['hello world', 'javascript is fun', 'i like programming']
Combining Projection and Filtering

JavaScript seamlessly integrates projection and filtering. Now, let's lowercase sentences containing "JAVASCRIPT" while dismissing others:

const sentences = ["HELLO WORLD", "JAVASCRIPT IS FUN", "I LIKE PROGRAMMING"];  // our data stream

// filter selects sentences containing 'JAVASCRIPT'
const filteredSentences = sentences.filter(sentence => sentence.includes("JAVASCRIPT"));

// map applies the arrow function to each filtered sentence, converting it to lowercase
const lowerFilteredSentences = filteredSentences.map(sentence => sentence.toLowerCase());

console.log(lowerFilteredSentences);  // prints: ['javascript is fun']
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