1

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?

1
  • 4
    Javascript is not Python.The array comprehensions is non-standard in Javascript. For future-facing usages, consider using Array.prototype.map, Array.prototype.filter, arrow functions, and spread syntax. Commented Oct 23, 2017 at 10:18

1 Answer 1

2

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]));

Sign up to request clarification or add additional context in comments.

2 Comments

To answer my original question using maps I'd do: b = a.map(([x,y]) => [x*2, y]) Thanks for your post. I'll avoid array comprehensions!
@TimMahrt, yes..this is also one solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.