2

I have a string:

var string = "test,test2";

That I turn into an array:

var array = string.split(",");

Then I wrap that array into a larger array:

var paragraphs = [array];

Which outputs:

[['test','test2']]

But I need it to output:

[['test'],['test2']]

Any clue how I can do this?

3
  • 1
    Iterate array and push them into paragraphs as .push([arrayItem]) Commented Jun 20, 2017 at 19:08
  • why... that doesn't make sense. Why would you have arrays that only have one index ever? wouldn't ['test','test2'] make more sense? Commented Jun 20, 2017 at 19:20
  • I would have done what @SterlingArcher had done here, but nem035's solution is more professional! Commented Jun 20, 2017 at 20:34

4 Answers 4

7

Just map each item into an array containing that item:

var string = "test,test2";
var result = string.split(",").map(x => [x]);
                           // ^--------------
console.log(result);

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

2 Comments

This did it! Thanks!!
@ChrisOlson, please accept the answer if it worked for you.
1

let test_string = "test,test2";

let result = test_string.split(',').map(item => [item])

console.log(result)

Comments

0

You can get expected result using array Concatenation.

var string = "test,test2";
var array = string.split(",");
var finalArray=[[array[0]]].concat([[array[1]]])
console.log(JSON.stringify(finalArray));

Comments

-1

What version of JavaScript are you targeting?

This might be a general answer:

var arr = "test,test2".split(",");
var i = arr.length;
while(i--)
    arr[i] = [arr[i]];

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.