bla9kdog
bla9kdog

Reputation: 19

How to print out a simple horizontal chart? JavaScript

So I just started learning a JS and I can't figure out how to print the asterisks like this:

* * * * *
* * *
* * * * * * *

I could use some help since I am a complete beginner at JS.

I tried based on this example but I can't make it work:

// Square Rectangle

function print_rectangle(x, y) {
  var a, b;
  for (a = 1; a <= x; a++) {
    for (b = 1; b <= y; b++) {
      if (a == 1 || a == x || b == 1 || b == y)
        document.write("*");
      else
        document.write("&nbsp;&nbsp;");
    }
    document.write("<br>");
  }
}


var rows = 5,
  columns = 5;
print_rectangle(rows, columns);

Upvotes: 1

Views: 59

Answers (1)

Michael M.
Michael M.

Reputation: 11080

First, think about what your input needs to be. If you want to make a chart of some data, then you should be passing your function an array.

With that array, your function should loop over every element and print that many asterisks. If your array has very high numbers, you might want to add a scale parameter, then divide each number by the scale. Like this:

function plot(scale, data) {
  let ret = ''
  for (let el of data) {
    ret += '*'.repeat(Math.floor(el/scale));
    ret += '\n';
  }
  return ret;
}

console.log(plot(1, [1, 2, 3]));
console.log(plot(1, [5, 1, 4]));
console.log(plot(100, [400, 100, 300]));

Upvotes: 3

Related Questions