Tim Mahrt
Tim Mahrt

Reputation: 103

How to make a multidimensional array comprehension in javascript?

Given: a = [[1,2],[3,4],]

I want to do something like:

a = [for ([x,y] of a) [x*2,y]];

But this gives me the next error:

'SyntaxError: missing variable name'

I am able to do the following:

a = [for (z of a) [z[0]*2,z[1]]];

I prefer the first notation as the internal variables (x and y) can be given descriptive names making the code easier to read. Is it possible?

Upvotes: 1

Views: 219

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

The array comprehensions is non-standard in Javascript. For future-facing usages, just use Array.prototype.map, Array.prototype.filter, arrow functions, and spread syntax features of Javascript language.

For this example, use map method which accepts as parameter a callback provided function.

let a = [[1,2],[3,4]];
console.log(a.map(([x,y]) => [x*2, y]));

Upvotes: 2

Related Questions