Add a string to an existing array at a specific Index help

Add a string to an existing array at a specific Index help
0

#1

Hey guys I was trying to do a coding challenge recently and I’m trying to figure out how to add a string item into an existing array. For example:

var strArray = ["Mountain", "Pepsi", "Coke"]

How would I add the string “Dew” at the end of the first element in the array?


#2

What do you mean by at the end of the first element?

You can add a string at the end of an array by using .push() (if this is what you mean):

strArray.push('Dew');


#3

I assume you are asking how to insert “Dew” as an element between the “Mountain” and “Pepsi” elements. To do that, you should read about Array.prototype.splice.


#4

I’m sorry I wasn’t clear I want to transform this:

var strArray = ["Mountain", "Pepsi", "Coke"]

Into this:

var strArray = ["Mountain Dew", "Pepsi", "Coke"]

#5

Do you know how to reference a specific array element?

If so, then you could assign that element the concatenation of that same element’s value and the string " Dew" (notice the space before Dew).


#6

It’s easy to do that.

You just need to change the string in question.

var arr = ["Mountain", "Pepsi", "Coke"];

arr[0] = 'Mountain Dew'; // Mountain is at index 0.
 
console.log(arr); // output: Mountain Dew,Pepsi,Coke

#7

Since @clevious already showed you how to do it, I will show you what I was suggesting which does not repeat the word “Mountain”.

arr[0] += ' Dew';