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?

Angular noob
  • 437
  • 4
  • 11
  • Checkout [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) – Jason Cust May 05 '15 at 15:00
  • Please see #ninjagecko `Array.prototype.chunk` answer [here](http://stackoverflow.com/a/10456644/2365792). To use on your `text` array, do it like `var argument = text.chunk(text.length);` – Tim Rijavec May 05 '15 at 15:02
  • possible duplicate of [Split array into chunks](http://stackoverflow.com/questions/8495687/split-array-into-chunks) – Tim Rijavec May 05 '15 at 15:03

1 Answers1

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]);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Perfect. How do I enable ES6 in Node? Are arrow functions supported yet? – Angular noob May 05 '15 at 15:38
  • @Angularnoob: Ah, looks like they aren't *quite* yet: https://github.com/joyent/node/wiki/ES6-%28a.k.a.-Harmony%29-Features-Implemented-in-V8-and-Available-in-Node (right at the bottom, but I figured the page as a whole was useful to you). – T.J. Crowder May 05 '15 at 15:54
  • @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**! – Angular noob May 05 '15 at 16:46
  • @Angularnoob: It's getting here. :-) About two years behind schedule, which isn't as bad as it could be as these things go... – T.J. Crowder May 05 '15 at 16:58