0

I have some text that I receive from the user:

var text = ['Hello', 'World']; // this is the product of string.split(',')

I need to convert it into an array like this one:

var argument = [['Hello'], ['World']];

I need the input in this format so I can send multiple values to the db.

How can I do this elegantly?

3
  • Checkout map Commented May 5, 2015 at 15:00
  • Please see #ninjagecko Array.prototype.chunk answer here. To use on your text array, do it like var argument = text.chunk(text.length); Commented May 5, 2015 at 15:02
  • possible duplicate of Split array into chunks Commented May 5, 2015 at 15:03

1 Answer 1

3

I can't think of anything more elegant for this than map:

E.g.:

var argument = originalString.split(",").map(function(entry) {
    return [entry];
});

Or if you've enabled ES6 on your NodeJS installation:

var argument = originalString.split(",").map((entry) => [entry]);
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect. How do I enable ES6 in Node? Are arrow functions supported yet?
@Angularnoob: Ah, looks like they aren't quite yet: github.com/joyent/node/wiki/… (right at the bottom, but I figured the page as a whole was useful to you).
@That is too bad, man. I am not much of a JS coder (evidently,) but it seems like ES 6 has been imminent for ages!
@Angularnoob: It's getting here. :-) About two years behind schedule, which isn't as bad as it could be as these things go...

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.