Aymon Fournier
Aymon Fournier

Reputation: 4433

What's the equivalent of a list comprehension like this one in ES2016 or greater?

Python 3.6:

[f"Cat #{n}" for n in range(5)]

gives

['Cat #0', 'Cat #1', 'Cat #2', 'Cat #3', 'Cat #4']

New to JavaScript, What's the equivalent in new EcmaScript?

Upvotes: 10

Views: 6806

Answers (4)

Slai
Slai

Reputation: 22906

console.log( [...Array(5)].map((v, i) => `Cat #${i}`) )

If it has to work in IE too :

console.log( Array.apply(0, Array(5)).map(function(v, i) { return 'Cat #' + i; }) )

Upvotes: 4

shinji709
shinji709

Reputation: 41

Use the combination of Generator and Spread Operator.

ES2015:

[...(function*(){for(let n=0;n<5;)yield'Cat #'+n++})()]

gives

["Cat #0", "Cat #1", "Cat #2", "Cat #3", "Cat #4"]

Upvotes: 4

Ori Drori
Ori Drori

Reputation: 193358

Array comprehension in JS was proposed for ES2016, but never made it to the final release. Firefox supported comprehensions for a time, but the support was dropped in later versions.

You can use Array#from to get something close to comprehension.

const result = Array.from({ length: 5 }, (_, k) => `Cat #${k}`);

console.log(result);

Upvotes: 23

Rob M.
Rob M.

Reputation: 36541

There isn't anything so lovely in Javascript. To the best of my knowledge, you need to create a new Array and use .fill() to make each element something other than undefined. Then you can use .map and return/work with the array index rather than the value. Something like this:

console.log((new Array(5)).fill(0).map((x,i) => `Cat ${i}`))

You may find generators useful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Generator_comprehensions

Upvotes: 10

Related Questions