Search⌘ K
AI Features

SQL and Map-Reduce-Filter

Explore how to convert SQL queries into JavaScript by applying map, reduce, and filter functions without loops or if statements. Understand the process of joining data arrays, counting items, and summing values, all while practicing modern ES6 coding techniques useful for job interviews.

We'll cover the following...

Exercise:

Suppose the following tables are given in the form of arrays of objects:

Node.js
var inventory = [
{
id: 1,
owner: 1,
name: 'Sword',
weight: 10,
value: 100
},
{
id: 2,
owner: 1,
name: 'Shield',
weight: 20,
value: 50
},
{
id: 3,
owner: 2,
name: 'Sword',
weight: 9,
value: 150
}
];
var characters = [
{
id: 1,
name: 'Zsolt',
points: 500,
level: 5
},
{
id: 2,
name: 'Ron',
points: 200,
level: 2
},
{
id: 3,
name: 'Jack',
points: 0,
level: 1
}
]
console.log(characters.map( c => c.name ));

Translate the following SQL query using map, reduce, and filter:

MySQL
SELECT characters.name, SUM( inventory.value ) AS totalValue
FROM characters, inventory
WHERE characters.id = inventory.owner
GROUP BY characters.name

You are not allowed to use loops, if statements, logical operators, or the ternary operator.

Solution:

We need to list all character names and the sum of the value of their items.

As characters and inventory are arrays, we can use the map, reduce, and filter. ...