Mircea
Mircea

Reputation: 11593

Javascript append an element to Array at specific index

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.

Upvotes: 1

Views: 2042

Answers (4)

Gordon Gustafson
Gordon Gustafson

Reputation: 41209

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) ;

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186552

To concatenate to an element that's a string:

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

To reassign it:

myArr[2] = 'foo';

Upvotes: -1

Free Consulting
Free Consulting

Reputation: 4402

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

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163228

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

Upvotes: 6

Related Questions