0

I have an array like this:

[[a, aa], [b, bb], [c, cc]]

I want to loop through it in Coffeescript. Actually I want to put those values as attributes for some function:

someFunc(a, aa)

for one dimensional array I can loop with construction

for value in array

However I have no idea how to do it for 2D array. And I wander about the best way to do it.

I'll appreciate any help!

2 Answers 2

2

Something like [['a', 'aa'], ['b', 'bb'], ['c', 'cc']] isn't actually a two dimensional array, there is no such thing in JavaScript or CoffeeScript. That's actually an array of arrays. So if you do this:

array = [['a', 'aa'], ['b', 'bb'], ['c', 'cc']]
for value in array
    #...

then value will be ['a', 'aa'], ['b', 'bb'], and finally ['c', 'cc'] inside the loop body. Then you could say:

array = [['a', 'aa'], ['b', 'bb'], ['c', 'cc']]
for value in array
    someFunc(value[0], value[1])

or you could use a splat to unpack the value array automatically:

array = [['a', 'aa'], ['b', 'bb'], ['c', 'cc']]
for value in array
    someFunc(value...)
    # ------------^^^

That splat is just a hidden Function.prototype.apply call and is equivalent to:

someFunc.apply(null, value)

If you need to iterate over value then you'd just throw another loop in:

array = [['a', 'aa'], ['b', 'bb'], ['c', 'cc']]
for value in array
    for e in value
        # do things with `e`, it will be 'a', 'aa', 'b', ...
Sign up to request clarification or add additional context in comments.

Comments

1

You could use some destructuring assignment:

array = [['a', 'aa'], ['b', 'bb'], ['c', 'cc']]
for [arg1, arg2] in array
    # console.log arg1, arg2
    someFunc(arg1, arg2)

Comments

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.