1

I have a dynamically generated Array:

myArr = ["val0a", "val1a", "val2a"... "val600a"]

I am having problems appending a new array values to this array in a loop. My Array should look like this after the append:

myArr = ["val0a", "val1a val1b", "val2a val2b"... "val600a"]

Please note that the new array and the old one do not have the same length.

How can I do this? It have to be something simple but I can't figure it out.

2
  • I'm confused - you want to append to the array (per your question title), or append to an element in the array, per your example Commented Nov 24, 2010 at 16:51
  • append to an element in the array. I probably need to fix my title Commented Nov 24, 2010 at 16:52

4 Answers 4

6

You can write a function along the lines of this:

Array.prototype.appendStringToElementAtIndex = function(index, str) {
    if(typeof this[index] === 'undefined' || typeof this[index] !== 'string') return false;
    this[index] += ' ' + str;
};


myArr = ["val0a", "val1a", "val2a"];
myArr.appendStringToElementAtIndex(1, "val1b");

console.log(myArr.join(', ')); //val0a, val1a val1b, val2a
Sign up to request clarification or add additional context in comments.

Comments

0
myArr.push(myArr[myArr.length - 1].split(" ").push("val42").join(" "));  // even

Comments

0

to append a value to an element of an array you can just do this:

myArr = ["val0a", "val1a", "val2a"... "val600a"];
indexToAppendTo = 2;
val2 = "val2b"
myArr[ indexToAppendTo ] += (" " + val2) ;

Comments

-1

To concatenate to an element that's a string:

myArr[2] = myArr[2] += 'blah';

To reassign it:

myArr[2] = 'foo';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.