VictorChars96
VictorChars96

Reputation: 63

How to print an increase and decrease array in JavaScript

For example

The list should be print like this:

0
0 1 
0 1 2
0 1 2 3
0 1 2 3
0 1 2
0 1
0

Upvotes: 0

Views: 154

Answers (3)

Daisho Arch
Daisho Arch

Reputation: 519

In my opinion this method is the easiest because of it's ES6 syntax and the use of simple Array methods.

let arr = (
    Array.from(
        {length: 4},
        (_, i) => 
            Array
                .from({length: i+1}, (_, j) => j)
                .join(' ')
    )
)

console.log(arr.join('\n'))
console.log(arr.reverse().join('\n'))

Here is the same thing, but with for loops:

let arr = [];
for(const [lineI] of Array.from({length: 4}).entries()) {
    let l = [];
    for(const [numI] of Array.from({length: lineI+1}).entries()) {
        l.push(numI);
    }
    arr.push(l);
    console.log(l.join(' '));
}
console.log(arr.reverse().map(line => line.join(' ')).join('\n'))

Upvotes: 2

Nicholas Carey
Nicholas Carey

Reputation: 74307

This is a nice way to this:

const list = [1, 2, 3, 4];

let i = 0 ;
while ( i < list.length ) {
  console.log( list.slice(0,++i).join(' ') );
}
while ( i >= 0 ) {
  console.log( list.slice(0,i--).join(' ') );
}

Upvotes: 1

Spectric
Spectric

Reputation: 31992

Use a nested for loop:

const list = [0, 1, 2, 3]
for (let i = 1; i <= list.length; i++) {
  var str = '';
  for (let j = 0; j < i; j++) {
    str += list[j]+' ';
  }
  console.log(str);
}


for (let i = list.length; i > 0; i--) {
  var str = '';
  for (let j = 0; j < i; j++) {
    str += list[j]+' ';
  }
  console.log(str);
}

Upvotes: 0

Related Questions