Search code examples
javascriptalphabet

How can I make a pyramid based on alphabet?


So how can I make multiply alphabet letters? I'm using an array with strings and I want to multiply them by their index.

A
BB
CCC
DDDD
EEEEE 

etc.

<script>
    window.onload = start;
    var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", 
                   "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
    var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 
                   21, 22, 23, 24, 25, 26];

    function start() {
        document.getElementById("randomize").onclick = execute;
    }

    function execute() {
        for (var i = 0; i < letters.length; i++) {
            for (var j = 0; j <= numbers.length; j++) {
                var product = numbers.length * letters[i];
                document.getElementById("output").innerHTML += "<li>" + letters[i] + "</li>";
            }
        }
    }
</script>

Solution

  • You did almost everything perfect, except, you need to get the numbers[i] value and not the length.

    window.onload = start;
    
    var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", 
                   "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
    
    var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                   21, 22, 23, 24, 25, 26];
    
    function start() {
      document.getElementById("randomize").onclick = execute;
    }
    
    
    function execute() {
      for (var i = 0; i < letters.length; i++) {
        var product = "";
        for (var j = 0; j < numbers[i]; j++)
          product += letters[i];
        document.getElementById("output").innerHTML += "<li>" + product + "</li>";
      }
    }
    li {font-family: 'Consolas', monospace;}
    <button id="randomize">Randomize</button>
    <div id="output"></div>