1

Can someone explain to me if it is possible to create a new array from an array and a string? Example:

I have this array:

let array = ['value1', 'value2']

And this string:

let testString = 'value3';

and I want to create an array from these two, which should look like this:

['value1', 'value2', 'value3']

How do I get this result? Is there a direct method for this or do I have to solve this with a loop?

  • `array.concat(testSring)` will create a new array with the value added `array.push(testString)` will add it to the current array. – VLAZ Jan 29 '21 at 11:40

2 Answers2

0

Yes you can use concat which will return a new array or you can use ES6 spread operator to create a new array with the new element.

const array = ['value1', 'value2'];
const testString= 'value3';

//Concat method
const newArrayMethod1 = array.concat(testString);

// ES6 spread operator method
const newArrayMethod2 = [...array, testString];
Castihell
  • 11
  • 2
0

let array = ['value1', 'value2']
let testString = 'value3';

array.push(testString)
console.log(array)
M.S.Udhaya Raj
  • 150
  • 1
  • 12