How to usearray manipulation and join() method in Javascript

In JavaScript, an array is populated incrementally to form each line of the pattern. The join() method converts the array elements into a string, separating them with spaces. here we are creating a pyramid by using a number pattern.

Example: We are using nested loops, array manipulation, and the join() method, this JavaScript code prints a number pattern with spaces, where numbers increase along each row up to 5.

Javascript




const n = 5;
for (let i = 1; i <= n; i++) {
    let arr = [];
    let count = 1;
    for (let j = 1; j <= 2 * n; ++j) {
        if (i + j >= n + 1 && (i >= j - n + 1)) {
            arr.push(count);
            count++;
        } else {
            arr.push(' ');
        }
    }
    console.log(arr.join(' '));
}


Output

        1          
      1 2 3        
    1 2 3 4 5      
  1 2 3 4 5 6 7    
1 2 3 4 5 6 7 8 9  


JavaScript Program to Print Number Pattern

The idea of pattern-based programs is to understand the concept of nesting for loops and how and where to place the alphabet/numbers/stars to make the desired pattern.

These are the following approaches to printing different types of number patterns:

Table of Content

  • Using nested loops
  • Using array manipulation and join() method

Similar Reads

Approach 1: Using nested loops

In this approach Nested loops iterate through rows and columns, incrementing row count in the outer loop and column count inner loop, to print desired patterns or structures like right angled trangle....

Approach 2: Using array manipulation and join() method

...