4

I would like to create a miltidimentional array as follows so

var multi-arr = [
 ["A,2,5"], 
 ["B,4,4"], 
 ["C,4,4"]
 ]

from string values gotten from the database using ajax.

string data gotten from db delimited by #

var string = "A,2,5# B,4,4# C,4,4";

I split the string by a '#' delimiter

arr1=string.split(/\s*\#\s*/g);

creating the array below

var arr = ["A,2,5", "B,4,4", "C,4,4"];

I want to further split the items in the above array using the comma ',' as a delimiter and create a multidimensional array

My problem is the loop only pushes in the last item in the array

for (i = 0; i < arr.length; i++) { 
 var arr2 = [];
 arr2[i]=arr2.push(arr1[i].split(/\s*,円\s*/g));
 }
console.log(arr2);

What am i doing wrong? or what can i do better?

asked Jan 24, 2016 at 1:28
1
  • why not rewrite it to JSON and just parse that? Commented Jan 24, 2016 at 1:33

6 Answers 6

4

You could split it, but you have all the delimiters in place anyway, just rewrite your string to be JSON-conformant and run it through JSON.parse():

// base string
var str = "A,2,5# B,4,4# C,4,4";
// quote text data. If the array was plain number data, we don't even need this step.
var quoted = str.replace(/([a-zA-Z]+)/g,'"1ドル"');
// rewrite to JSON form for a nested array
var jsonStr = "[[" + quoted.replace(/#/g,'],[') + "]]";
// done, just tell the JSON parser to do what it needs to do.
var arr = JSON.parse(jsonStr);

And that's it, arr is now the nested array [["A",2,5],["B",4,4],["C",4,4]].

answered Jan 24, 2016 at 1:37
Sign up to request clarification or add additional context in comments.

Comments

2

This should work

var str = "A,2,5# B,4,4# C,4,4";
var arr = str.split(/\s*\#\s*/g);
 for (var i = 0; i < arr.length; i++) { 
 arr[i]=arr[i].split(/\s*,円\s*/g);
 }
console.log(arr)

In your solution var arr2 = []; needs to be outside the for loop, or it gets redefined everytime. However, we don't really need to define a separate var and simply update the original array.

answered Jan 24, 2016 at 1:31

Comments

1

The var statement should be outside the for loop and you don't need to do the assignment and the push.

var i;
var string = "A,2,5# B,4,4# C,4,4";
var arr1 = string.split("#");
var arr2 = [];
for (i = 0; i < arr1.length; i++) {
 arr2[i]=arr1[i].split(",");
} 
console.log(arr2);

As suggested by Mike 'Pomax' - you could return the data from the server as JSON. If you're using PHP, that can be done like so:

header('Content-Type: application/json');
echo json_encode($queryResult);
exit;
answered Jan 24, 2016 at 1:33

3 Comments

That's what i was doing wrong. But i'll use Mike 'Pomax' s method.
just remember not to trust your server's response (becaue 404s, 500s, etc), and use a try/catch, because if you're feeding data to JSON.parse() without knowing for certain what's in it (like in my answer), it can throw and cause your script to error out.
For fun - you can compare the performance of these solutions: jsperf.com/string-to-multi-array. Performance will likely vary on different data sets, one one of these solutions has an additional check on the content of the array.
1

Here is a simple solution that should work on modern browsers:

var string = "A,2,5# B,4,4# C,4,4";
var multiArray = string.split(/\s*\#\s*/g).map(function(substr) {
 return [substr];
});
answered Jan 24, 2016 at 1:38

Comments

0

You just need to loop over each element in the array again after your first split. I would use Array.prototype.map as it will return you a new array without mutating the original.

I also did a check to see if the value in the inner array was a number. if it was it is parsed to an actual number.

var arr = ["A,2,5", "B,4,4", "C,4,4"];
console.log(arr);
var multidimensional = arr.map(function(item) {
 // you need to split the elements in your array
 return item.split(/,/).map(function(val) {
 // you may as well check if it's a string or a Number
 return parseIfNumber(val);
 })
});
console.log(multidimensional);
// helper functioon
function parseIfNumber(val) {
 return /^[0-9.-]+$/.test(val) 
 ? Number(val) 
 : val;
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

answered Jan 24, 2016 at 1:39

Comments

0

From your current arr variable - ["A,2,5", "B,4,4", "C,4,4"] - you can create your multi_arr variable like so:

var multi_arr = [];
arr.forEach(function(a) {
 multi_arr.push([a]);
});

Keep in mind, this will create the array exactly as the example of what you were looking for, which was this:

var multi-arr = [
 ["A,2,5"], 
 ["B,4,4"], 
 ["C,4,4"]
 ]

If you want each of the items in the inner arrays to be split as well, this will work for you:

var multi_arr = [];
arr.forEach(function(a) {
 multi_arr.push(a.split(','));
});
answered Jan 24, 2016 at 1:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.