Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use reduce instead of nested for loops?

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading