Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional way to iterate over range (ES6/7) [duplicate]

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.

like image 383
bsr Avatar asked Oct 15 '22 11:10

bsr


1 Answers

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);
like image 65
Pavlo Avatar answered Oct 20 '22 19:10

Pavlo