MarleyFree
MarleyFree

Reputation: 11

Convert a 1D array of strings into a 2D array

I am a bit of a novice here, so I will just jump right into the example of the issue I am having:

I want to convert this: "cat@dog%arm@hand%tree@apple..."

into this:

cat | dog
arm | hand
tree| apple
..etc

As in, 2 columns in the spreadsheet, or a 2D array. Isolating the strings using has not been difficult, it is the array manipulation that is stumping me.

Here is one attempt: `

function key_abb(input) {
  if(input.map) { 
    return input.map(key_abb);
  }else {
    var temp = input.toString();
    temp = temp.replace("abbreviated-name=", "");
    temp = temp.replace("name=", "");
    return temp;
  }
}`

input being an input range that is formatted like this:

|abbreviated-name="cat"  name="dog"  |
|abbreviated-name="arm"  name="hand" |...

Unfortunately this is still just returning the two strings within the same column, so the only thing that was accomplished was that the extra text was removed, I am not sure how to create the output array that I would like. Thank you!

Upvotes: 1

Views: 115

Answers (2)

Dave
Dave

Reputation: 10924

Here's another option using Array.map():

var str = 'cat@dog%arm@hand%tree@apple';
var data = str.split('%').map(function(item) {
  return item.split('@');
});
    
console.log(data);

Upvotes: 1

Marty
Marty

Reputation: 39466

Here you go:

var str = 'cat@dog%arm@hand%tree@apple';
var data = str.split('%');

for (var i = 0; i < data.length; i++) {
    data[i] = data[i].split('@');
}
    
console.log(data);

Results in:

[
    ["cat", "dog"],
    ["arm", "hand"],
    ["tree", "apple"]
]

Upvotes: 2

Related Questions