Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to split comma and semicolon separated string into a two-dimensional array in JavaScript ?
Let's say we have a variable "users" that contains the following string of text where each user is separated by a semicolon and each attribute of each users is separated by a comma ?
const users = 'Bob,1234,Bob@example.com;Mark,5678,Mark@example.com';
We are required to write a JavaScript function that takes in one such string and splits this into a multidimensional array that looks like this ?
const arr = [ ['Bob', 1234, 'Bob@example.com'], ['Mark', 5678, 'Mark@example.com'] ];
Method 1: Using split() and for Loop
The most straightforward approach is to first split by semicolons to get individual records, then split each record by commas:
const users = 'Bob,1234,Bob@example.com;Mark,5678,Mark@example.com';
const splitByPunctuations = (str = '') => {
let res = [];
res = str.split(';');
for(let i = 0; i < res.length; i++){
res[i] = res[i].split(',');
};
return res;
};
console.log(splitByPunctuations(users));
[ [ 'Bob', '1234', 'Bob@example.com' ], [ 'Mark', '5678', 'Mark@example.com' ] ]
Method 2: Using map() Function
A more functional approach using the map() method for cleaner code:
const users = 'Bob,1234,Bob@example.com;Mark,5678,Mark@example.com';
const splitString = (str) => {
return str.split(';').map(row => row.split(','));
};
console.log(splitString(users));
[ [ 'Bob', '1234', 'Bob@example.com' ], [ 'Mark', '5678', 'Mark@example.com' ] ]
Method 3: One-liner Arrow Function
The most concise approach using a single arrow function expression:
const users = 'Bob,1234,Bob@example.com;Mark,5678,Mark@example.com';
const parseUsers = str => str.split(';').map(row => row.split(','));
console.log(parseUsers(users));
[ [ 'Bob', '1234', 'Bob@example.com' ], [ 'Mark', '5678', 'Mark@example.com' ] ]
Comparison
| Method | Code Length | Readability | Performance |
|---|---|---|---|
| For Loop | Longer | Good | Fastest |
| map() Function | Medium | Excellent | Good |
| One-liner | Shortest | Good | Good |
Conclusion
The map() approach is generally recommended for its readability and functional programming style. Use the for loop method when performance is critical for large datasets.
