functional way to iterate over range (ES6/7)

bsr picture bsr · Jun 4, 2015 · Viewed 108.1k times · Source

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.

Answer

Pavlo picture Pavlo · Jun 4, 2015

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

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