1

I have some data and I want to split it twice. The data looks something like this:

var data = ['a1 b1 c1', 'a2 b2 c2Xa3 b3 c3Xa4 b4 c4', 'a5 b5 c5', 'a6 b6 c6Xa7 b7 c7', 'a8 b8 c8'];

As a first delimiter I use the 'X' character and this works fine:

var firstSplit = new Array(new Array());
    for(var i = 0; i < data.length; i++)
        firstSplit[i] = data[i].split('X');

But when I use the whitespace between the elements as a delimiter I get "Uncaught TypeError: Cannot set property '0' of undefined", on the line of the second split.

var secondSplit = new Array(new Array(new Array()));
for(var i = 0; i < firstSplit.length; i++) {
    for(var j = 0; j < firstSplit[i].length; j++)
        secondSplit[i][j] = firstSplit[i][j].split(' ');
    }
2
  • What is the desired result? Commented Aug 1, 2017 at 8:11
  • Every element should have been a separate one, but they already answered it. Thanks anyway! Commented Aug 6, 2017 at 19:34

4 Answers 4

2

You could first split by X and map the result of the splitted values by space .

var data = ['a1 b1 c1', 'a2 b2 c2Xa3 b3 c3Xa4 b4 c4', 'a5 b5 c5', 'a6 b6 c6Xa7 b7 c7', 'a8 b8 c8'],
    result = data.map(a => a.split('X').map(b => b.split(' ')));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

1

Array.map would be a better way

var data = ['a1 b1 c1', 'a2 b2 c2Xa3 b3 c3Xa4 b4 c4', 'a5 b5 c5', 'a6 b6 c6Xa7 b7 c7', 'a8 b8 c8'];

var result = data.map( (str) => {
   return str.split(' ');
});

console.log(result);

Comments

0

Use .push to push each element to your result array.

var data = ['a1 b1 c1', 'a2 b2 c2Xa3 b3 c3Xa4 b4 c4', 'a5 b5 c5', 'a6 b6 c6Xa7 b7 c7', 'a8 b8 c8'];

var firstSplit = new Array(new Array());
for (var i = 0; i < data.length; i++) {
  firstSplit[i] = data[i].split('X');
}

var secondSplit = [];
for (var i = 0; i < firstSplit.length; i++) {
  for (var j = 0; j < firstSplit[i].length; j++) {
    secondSplit.push(firstSplit[i][j].split(' '));
  }
}

console.log(secondSplit)

Comments

0

Convert space to (-) then do you work

var str;
var firstSplit = new Array(new Array());
for(var i = 0; i < data.length; i++){
str = data[i].replace(/\s+/g, '-');
    firstSplit[i] = str.split('-');
}

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.