0

I have arrays like:

a = ['a', 'b', 'c']
b = [1, 2, 3]

and I would like to get:

[['a', 1], ['b', 2], ['c', 3]]

Is there some elegant (functional) way to do this, or will I have to use loops and indexes?

3
  • 1
    why elegant? what does not work? Commented Apr 26, 2020 at 20:49
  • I think you are looking for this: stackoverflow.com/questions/22015684/… Commented Apr 26, 2020 at 20:51
  • @493msi Thanks, couldn't find it :) Commented Apr 26, 2020 at 20:52

2 Answers 2

3

Would you consider something like this "elegant"?

a.map((x, idx) => [x, b[idx]]);
Sign up to request clarification or add additional context in comments.

1 Comment

I'd use slightly different variable names and i not idx but this is good
0

Option 1

var a = ['a', 'b', 'c']
    b = [1, 2, 3];

var zip = [];
for (var i = 0; i < a.length; i++){
   zip.push([a[i], b[i]]);
}

OR to use fewer lines i.e. more 'elegant' approach:

Option 2

var a = ['a', 'b', 'c']
    b = [1, 2, 3];

var zip = (b, a) => b.map((k, i) => [k, a[i]]);
// Instead of the for loop
// [['a', 1], ['b', 2], ['c', 3]]

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.