Weblurk Weblurk - 11 days ago 6
Javascript Question

In javscript, how can I split a string and then push something into the resulting array?

I have this string:

var fruits = "banana,apple";


And I'm trying to add fruits to it by converting it to an array and then pushing the new fruit like this:

var newFruit = "orange";
fruits
.split(",")
.push(newFruit);


But this doesn't work because
fruits.split(",")
doesn't seem to return a "normal" array, i.e I can't perform
push()
on it.

Is this somehow possible?

Answer

split does return a normal array. You are successfully calling push on it.

The problem is that you are then discarding the array so you can't do anything further with it.

Since push doesn't return the array itself, you have no way of using the array for anything further after calling push on it.

concat returns a new array that contains the additional values, but you would still have to do something with the array afterwards.

var fruits = "banana,apple";
var newFruit = "orange";
var myArray = fruits
  .split(",")
  .concat(newFruit);
console.log(myArray);