Monday, June 3, 2024
10
rated 0 times [  12] [ 2]  / answers: 1 / hits: 191739  / 9 Years ago, thu, june 4, 2015, 12:00:00

What is the best way to do the below in more functional way (with ES6/ES7)



let cols = [];
for (let i =0; i <= 7; i++) {
cols.push(i * i);
}
return cols;


I tried like,



return [ ...7 ].map(i => {
return i * i;
});


but that translated to



[].concat(7).map(function (n) {
return n * n;
});


which is not what I expected.



EDIT:



@pavlo. Indeed, that was a mistake. I was using JSX, and for example, I want 7 divs, (untested)



let cols = [];
for (let i =0; i <= 7; i++) {
cols.push(<div id={i}> ... </div>)
}
return cols;


so the idea was indeed to reduce the number of temp variables and procedural feel.


More From » functional-programming

 Answers
7

One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:


Array(8).fill(0).map((_, i) => i * i);

[#66326] Wednesday, June 3, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loric

Total Points: 110
Total Questions: 96
Total Answers: 91

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;