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? 😉
JavaScript
​x
13
13
1
let table = () => {
2
let x, y, sum;
3
let table = '';
4
​
5
for (y = 10; y <= 20; y++) {
6
for (x = 10; x <= 20; x++) {
7
sum = x * y;
8
table += `|${sum} `;
9
}
10
table += '|n';
11
}
12
result.innerText = table;
13
};
JavaScript
1
14
14
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8" />
5
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
6
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
<title>Task 4</title>
8
</head>
9
<body onload="table()">
10
<h2>Multiplication table</h2>
11
<div id="result"></div>
12
</body>
13
​
14
</html>
Advertisement
Answer
Yes it is possible. Since you have a nested for loop, you need two reduce
s: a reduce
per row and a reduce
for the entire table :
JavaScript
1
4
1
range.map(x =>
2
range.map(y => x * y).reduce((row, sum) => row + `|${sum} `), '')
3
.reduce((table, row) => table + row + '|n', '');
4
​
That being said, in your case you’d probably want to create an HTML table.
Snippet
JavaScript
1
7
1
let table = () => {
2
const range = Array.from({length: 11}, (x, i) => i + 10);
3
​
4
result.innerText = range.map(x =>
5
range.map(y => x * y).reduce((row, sum) => row + `|${sum} `), '')
6
.reduce((table, row) => table + row + '|n', '');
7
};
JavaScript
1
14
14
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8" />
5
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
6
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
<title>Task 4</title>
8
</head>
9
<body onload="table()">
10
<h2>Multiplication table</h2>
11
<div id="result"></div>
12
</body>
13
​
14
</html>