Sagive SEO Sagive SEO - 4 months ago 7
Javascript Question

Create a 2 levels array in javascript using split

I need to split a string into a two level array (or rather array inside and array with auto keys).

Say the string is:

item 10~item 11~item 12^ item 20~item 21~item 23^

i would like it to be in similar structure
i know php - hense the structure

array(
[0]=> array(
'item 10',
'item 11',
'item 12',
),
[1]=> array(
'item 20',
'item 21',
'item 22',
),
)


so...

the first split looks like this right?

function createDataArray(xData) {
xData.split("^");
--- WHAT DO I DO HERE? ---

}


Would appreciate your help

Answer

You can simply doing it like this, to get your desired output.

var str = 'item 10~item 11~item 12^ item 20~item 21~item 23^';

var arr = [];
str.split('^').forEach(function(v) {
  if (v) {
    arr.push(v.trim().split('~'));
  }
});

console.log(arr);

Comments