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!

asked Jul 16, 2014 at 14:30
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(",");
}
answered Jul 16, 2014 at 14:31
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"]]
answered Jul 16, 2014 at 14:31

1 Comment

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

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.