Skip to content

How to Create a Pyramid Array in Javascript

The challenge

Write a function that when given a number >= 0, returns an Array of ascending length subarrays.

pyramid() => [ ] pyramid(1) => [ [1] ] pyramid(2) => [ [1], [1, 1] ] pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]
Code language: JavaScript (javascript)

Note: the subarrays should be filled with 1s

The solution in Javascript

Option 1:

function pyramid(n) { const res = []; for(let i = ; i < n; i++){ res.push([...Array(i+1)].fill(1)) } return res; }
Code language: JavaScript (javascript)

Option 2:

function pyramid(n) { return Array(n).fill().map((e,i)=>Array(i+1).fill(1)) }
Code language: JavaScript (javascript)

Option 3:

const pyramid = n => Array(n).fill(1).map((x, i) => Array(i + 1).fill(1))
Code language: JavaScript (javascript)

Test cases to validate our solution

describe('basic tests', () => { it("Testing for 0", () => assert.deepEqual(pyramid(), [])); it("Testing for 1", () => assert.deepEqual(pyramid(1), [[1]])); it("Testing for 2", () => assert.deepEqual(pyramid(2), [[1], [1, 1]])); it("Testing for 3", () => assert.deepEqual(pyramid(3), [[1], [1, 1], [1, 1, 1]])); });
Code language: JavaScript (javascript)

See also  How to cleanup a /var/log/journal in Linux
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x