-3

Hello I have several strings like this:

Name,Age,Location and Jon,20,London

How can I turn these strings into an array of arrays like so: Not sure if the correct term is a multidimensional array or Jagged array...

[["Name","Age","Location"],["Jon","20","London"]]

What I Tried:

I looked into doing Javascript string split and .push, but no success.

var a = "Name,Age,Location" ;
var b = "Jon,20,London";
a.push(b);

What Worked (I was stuck at the .split part, Please see answer from "Sam"):

var a = 'Name,Age,Location'.split(',');
var b = 'Jon,20,London'.split(',');
var c = [];

c.push(a)
c.push(b)
console.log(JSON.stringify(c)) 
// [["Name","Age","Location"],["Jon","20","London"]] 
1ManStartup
  • 3,716
  • 4
  • 21
  • 26
  • You're not looking for `input.split(" and ").map(function(str) { return str.split(","); })`, are you? – Bergi Nov 18 '14 at 07:05
  • Put your efforts here, is it static or dynamic? – Sourabh Upadhyay Nov 18 '14 at 07:06
  • How did you try to apply `.split()`, because that would be the right method to use. – Ja͢ck Nov 18 '14 at 07:08
  • Your question must be more clear. You said 'You have several strings like this ...'. We need to know what that exactly means. You have these strings where exactly? – shinobi Nov 18 '14 at 07:10
  • Half of your question has already been answered here http://stackoverflow.com/questions/2858121/convert-comma-separated-string-to-array – Salman A Nov 18 '14 at 07:11
  • I used a nodejs/js module and it parses a csv file giving me a comma separated text, Name,Age,Location. It looks like an array, but I wanted to combine an array in an array. Concat combines them and the strings are already comma separated so not sure if split is still useful. – 1ManStartup Nov 18 '14 at 07:14

1 Answers1

1

How To Push Array into Array?

Given your code:

var a = "Name,Age,Location" ;
var b = "Jon,20,London";
a.push(b);

Here, both a and b are strings, not arrays; turning a string into an array using comma as the delimiter is simple, though:

var a = 'Name,Age,Location'.split(',');
var b = 'Jon,20,London'.split(',');
a.push(b);

Doing this will yield the following array:

['Name','Age','Location',['Jon',20,'London']]

Almost there; now you just need a separate array to put both a and b into:

var c = [a, b];
// or
var c = []; c.push(a); c.push(b);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309