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' )); |
* * * * * * * * * * * * * * * * * * * * * * * * *
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