Hernanda
Hernanda

Reputation: 57

How to split a content from 2D array into another 2D Javascript

I have a webpage that insert a table with a formated 2D array content. It looks like this (a string):

type[separator1]product1 Name[separator1]product 1 price[separator1]This is product1, as description[separator2]type[separator1]product2 Name[separator1]product 2 price[separator1]This is product2, as description

As you can see, I have a separator (formated), they are [separator1] and [separator2]. It is converted from normal 2D array, and when I manipulate it to make some 2D array, I got this:

[
"type[separator1]product1 Name[separator1]product 1 price[separator1]This is product1, as description",
"type[separator1]product2 Name[separator1]product 2 price[separator1]This is product2, as description"
]

Now, you can see that [separator1] is for separating array's content. And [separator2] is for separating between arrays. And you also can see that on my blockquoted 2D array formated content, the description has coma on it, which is becoming a problem because I want to split that inner array so I can get like array2[1], array2[2], etc. but I got problems, it said split is not a function. I want to access that 2D array from that separator so I can access array3[0][1] and others from that first String

This is the sample code

$('#tester').on('click', function() {
	var iContent = 'type[separator1]product1 Name[separator1]product 1 price[separator1]This is product1, as description[separator2]type[separator1]product2 Name[separator1]product 2 price[separator1]This is product2, as description';
	var str1 = iContent.split('[separator2]');
	var str2 = [];
	for (i=0; i<str1.length; i++) {
		str2.push(str1[i]);
	}
	//var str3 = str2.split('[separator1]');
	console.log('str2[0]: ' + str2[0]);
	console.log('str2[1]: ' + str2[1]);
	for (i=0; i<str2.length; i++) {
		str3.push(str2[i]);
	}
	console.log('iContent: ' + iContent);
	console.log('str1: ' + str1);
	console.log('str2: ' + str2);
	console.log('str3: ' + str3);
});

Upvotes: 1

Views: 36

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386660

For getting an array without separators, you could split and map the splitted stings.

var string = 'type[separator1]product1 Name[separator1]product 1 price[separator1]This is product1, as description[separator2]type[separator1]product2 Name[separator1]product 2 price[separator1]This is product2, as description',
    result = string.split('[separator2]').map(function (s) {
        return s.split('[separator1]');
    });
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions