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!
-
May I suggest a new data structure?Ryan– Ryan2014年07月16日 14:43:54 +00:00Commented Jul 16, 2014 at 14:43
2 Answers 2
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
Danilo Valente
11.4k8 gold badges55 silver badges71 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Cerbrus
"the .split method creates new String instances" What? You may need to clarify that a bit more.
Danilo Valente
@Cerbrus I meant that it creates a new array with strings and doesn't affect the value of the original string.
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
Cerbrus
73.3k19 gold badges138 silver badges151 bronze badges
1 Comment
Jason Griffith
Thank you so much! Too close to the forest to see the trees I suppose.
lang-js