0

So I have an array with the following values.

var keyVal = ["John, 2","Jane, 2", "John, 4","Jane, 5" ];

I'm trying to break out the array values into 2 it's own array so it would look like this.

var keyVal = [["John"][2],["Jane"][2], ["John"][2],["Jane"][2]];

I tried using a for loop like this:

for (var i=0; i< keyVal.length; i++ ){
                 keyVal[i].split(",");
             }

But for some reason when I go to check, nothing is changing.... What am I missing?

Thanks for your help!

1
  • May I suggest a new data structure? Commented Jul 16, 2014 at 14:43

2 Answers 2

1

According to MDN, the .split method creates a new array with strings and doesn't affect the value of the original string, so you must update the value of each item of the array:

for (var i=0; i< keyVal.length; i++ ){
    keyVal[i] = keyVal[i].split(",");
}
Sign up to request clarification or add additional context in comments.

2 Comments

"the .split method creates new String instances" What? You may need to clarify that a bit more.
@Cerbrus I meant that it creates a new array with strings and doesn't affect the value of the original string.
1

You're just missing the assignment in your loop:

for (var i=0; i< keyVal.length; i++ ){
    keyVal[i] = keyVal[i].split(",");
}

This will result in:

keyVal == [["John"," 2"],["Jane"," 2"],["John"," 4"],["Jane"," 5"]]

1 Comment

Thank you so much! Too close to the forest to see the trees I suppose.

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.