I’m trying to print out the multiplication table using js. Is there a cleaner way to do this than with nested for loops? I was thinking of reduce as an alternative. Any onther ideas out there? 😉
let table = () => {
let x, y, sum;
let table = '';
for (y = 10; y <= 20; y++) {
for (x = 10; x <= 20; x++) {
sum = x * y;
table += `|${sum} `;
}
table += '|n';
}
result.innerText = table;
};<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Task 4</title>
</head>
<body onload="table()">
<h2>Multiplication table</h2>
<div id="result"></div>
</body>
</html>Advertisement
Answer
Yes it is possible. Since you have a nested for loop, you need two reduces: a reduce per row and a reduce for the entire table :
range.map(x =>
range.map(y => x * y).reduce((row, sum) => row + `|${sum} `), '')
.reduce((table, row) => table + row + '|n', '');
That being said, in your case you’d probably want to create an HTML table.
Snippet
let table = () => {
const range = Array.from({length: 11}, (x, i) => i + 10);
result.innerText = range.map(x =>
range.map(y => x * y).reduce((row, sum) => row + `|${sum} `), '')
.reduce((table, row) => table + row + '|n', '');
};<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Task 4</title>
</head>
<body onload="table()">
<h2>Multiplication table</h2>
<div id="result"></div>
</body>
</html>