0

I have a string that looks like this:

str = {1|2|3|4|5}{a|b|c|d|e}

I want to split it into multiple arrays. One containing all the first elements in each {}, one containing the second element, etc. Like this:

arr_0 = [1,a]
arr_1 = [2,b]
arr_2 = [3,c]

.....

The best I can come up with is:

var str_array = str.split(/}{/);

for(var i = 0; i < str_array.length; i++){
    var str_row = str_array[i];
    var str_row_array = str_row.split('|');
    arr_0.push(str_row_array[0]);
    arr_1.push(str_row_array[1]);
    arr_2.push(str_row_array[2]);
    arr_3.push(str_row_array[3]);
    arr_4.push(str_row_array[4]);
}

Is there a better way to accomplish this?

1
  • str_row_array is an array, you can iterate over it, exactly the same way you iterate over str_array. arr_0 --- is a silly idea from the beginning, use arrays instead arr[0] Commented Apr 8, 2015 at 0:56

2 Answers 2

3

Try the following:

var zip = function(xs, ys) {
  var out = []
  for (var i = 0; i < xs.length; i++) {
    out[i] = [xs[i], ys[i]]
  }
  return out
}

var res = str
  .split(/\{|\}/) // ['', '1|2|3|4|5', '', 'a|b|c|d|e', '']
  .filter(Boolean) // ['1|2|3|4|5', 'a|b|c|d|e']
  .map(function(x){return x.split('|')}) // [['1','2','3','4','5'], ['a','b','c','d','e']]
  .reduce(zip)
/*^
[['1','a'],
 ['2','b'],
 ['3','c'],
 ['4','d'],
 ['5','e']]
*/
Sign up to request clarification or add additional context in comments.

Comments

1

Solution

var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) {
       return a.match(/[^|]+/g);
    }),
    i,
    result = {};

for (i = 0; i < str[0].length; i += 1) {
  result["arr_" + i] = [+str[0][i], str[1][i]];
}

How it works

The first part, takes the string, and splits it into the two halves. The map will return an array after splitting them after the |. So str is left equal to:

[
    [1,2,3,4,5],
    ['a', 'b', 'c', 'd', 'e']
]

The for loop will iterate over the [1,2,3,4,5] array and make the array with the appropriate values. The array's are stored in a object. The object we are using is called result. If you don't wish for it to be kept in result, read Other

Other

Because you can't make variable names from another variable, feel free to change result to window or maybe even this (I don't know if that'll work) You can also make this an array

Alternate

var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) { return a.match(/[^|]+/g); }),
    result = [];

for (var i = 0; i < str[0].length; i += 1) {
  result[i] = [+str[0][i], str[1][i]];
}

This is very similar except will generate an Array containing arrays like the other answers,

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.