I'm trying to create a function to create pascals triangle in javascript with Array.map() function.
Actually, i'm using this function :
let triangle = [],
maxRows = 5
// Columns
for (let i = 0; i < maxRows; i++) {
// Create new row
let row = [];
// Fill row
for (let j = 0; j <= i; j++) {
row.push(j === 0 || j === i ? 1 : triangle[i - 1][j - 1] + triangle[i - 1][j]);
}
// Add row to triangle
triangle.push(row);
}
console.log(triangle)
But I would like to use something like this :
let triangle = Array(maxRows).fill().map((row, i) => {
return Array(i + 1).fill().map((_, j) => {
return j === 0 || j === i ? 1 : triangle[i - 1][j - 1] + triangle[i - 1][j];
});
});
Is there a way to access triangle variable inside the second Array.map() ?
Since Array.prototype.map()
does not mutate source array in-place in real-time, but rather returns new array once it's done looping through your source array, there's actually no point of accessing triangle
- it will still be a scarce array of 5 items: [,,,,]
(returned by Array().fill()
), until the .map()
-loop is over.
To get around this, you may either come up with recursive approach, or use Array.prototype.reduce()
:
const maxRows = 5,
triangle = Array(maxRows)
.fill()
.reduce((acc, _, i) => {
const rowData = Array(i+1)
.fill()
.map((__,j) =>
!j || j == i
? 1
: acc[i-1][j-1] + acc[i-1][j]
)
acc.push(rowData)
return acc
}, [])
triangle.forEach(row => console.log(JSON.stringify(row)))
.as-console-wrapper{min-height:100%;}