Column-Wise Number Triangle in JavaScript

What You’ll Learn
How to print a triangle where numbers are filled down each column instead of left-to-right by rows.
This creates an interesting sequence like 2 6, 3 7 10, and so on.
⭐ Pattern Output
For n = 5, the pattern looks like this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15Complete JavaScript Program
We fill a 2D array column by column (only where col <= row), then print the rows.
const n = 5;
const tri = Array.from({ length: n }, () => []);
let value = 1;
// Fill column-wise
for (let col = 1; col <= n; col++) {
for (let row = col; row <= n; row++) {
tri[row - 1][col - 1] = value++;
}
}
// Print rows
for (let row = 1; row <= n; row++) {
console.log(tri[row - 1].slice(0, row).join(" "));
}🧠 How It Works
Create a triangle container
We store values in an array-of-arrays so we can fill first, then print cleanly.
Fill columns from left to right
For each column col, we fill rows col..n so the triangle shape is respected.
Increment value each placement
value++ ensures numbers are consecutive from 1 up to n(n+1)/2.
Print each row
Row r prints the first r values from that row array.
Column-wise triangle
Values increase down each column, producing the characteristic jumps (like 2 to 6).
Variation — Browser (aligned cells) Version
In the browser, we can print each value inside a fixed-width inline-block cell for alignment:
<!DOCTYPE html>
<html>
<body>
<script>
var n = 5;
var tri = Array.from({ length: n }, function () { return []; });
var value = 1;
for (var col = 1; col <= n; col++) {
for (var row = col; row <= n; row++) {
tri[row - 1][col - 1] = value++;
}
}
for (var r = 1; r <= n; r++) {
for (var c = 1; c <= r; c++) {
document.write('<span style="display:inline-block;width:3em;text-align:right">' + tri[r - 1][c - 1] + '</span>');
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
nto generate a larger triangle - Fill row-wise instead and compare the difference
- Auto-size cells using the max value length (for clean alignment)
- Color columns in browser mode to make the column-wise fill obvious
Avoid
- Forgetting that column
colstarts at rowcol(triangle shape breaks) - Using
document.writein real apps (fine for tutorials/demos) - Printing without fixed-width cells if you need alignment
Key Takeaways
This triangle is filled column-wise, not row-wise.
Each column fills from row col down to n.
Total printed values are n(n+1)/2.
Fixed-width cells help readability in both console and browser output.
❓ Frequently Asked Questions
n(n+1)/2) and pad each number to that width.Explore More JavaScript Number Patterns!
Try building a row-wise triangle next, then compare it with this column-wise version to deepen your loop intuition.
Column-wise vs row-wise filling is a common theme in matrix problems. Switching the fill order changes the pattern dramatically—even with the same numbers.
12 people found this page helpful
