How to use Array and Join methods In Javascript

In this approach, we use the Array and Join method to iterate over each row, constructing the strings of leading spaces and the β€œ*” pattern. The resulting string is then pushed into the array and last, the array is joined with the newline character, and the pattern is printed.

Syntax:

let newArray = Array(element1, element2, ..., elementN); 
let resultString = array.join(separator);

Example: To demonstrate printing an Inverted Pyramid in JavaScript using Array and the Join method in JavaScript.

Javascript




let r = 5;
let res = [];
 
for (let i = r; i >= 1; i--) {
    let s = Array(r - i + 1).join("  ");
    let stars = Array(2 * i - 1).fill("* ").join("");
    res.push(s + stars);
}
console.log(res.join('\n'));


Output

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


JavaScript Program to Print Inverted Pyramid

In JavaScript, the Inverted Pyramid is the geometric pattern of β€œ*” that is arranged in the format upside-down. This can be printed using various approaches like Looping, Recursion, and built-in methods.

Table of Content

  • Using Nested for Loop
  • Using Recursion
  • Using Array and Join methods

Similar Reads

Using Nested for Loop

This approach uses the for loop to print the inverted pyramid by using nested loops we control the spacing and the number of β€œ*” in each row. The outer loop mainly manages the rows and the inner loop controls the leading spaces and printing β€œ*” in the pattern....

Using Recursion

...

Using Array and Join methods

In the below approach, we have used the Recursive function which controls the row-wise printing by adjusting the leading spaces and the number of β€œ*” in each row. The base cases make sure that the recursion ends when the β€œn” exceeds the total rows....