1

I used another (my) way to store the elements of some array in another as a spread method. I used join method for this way, but the array contains only one. Here's my code:

const arr = [1, 2, 3];
const newArray = [eval(arr.join(', ')), 4, 5]

console.log(newArray) // [3, 4, 5]
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Majid Ainizoda
  • 89
  • 1
  • 12

2 Answers2

1

Try this:

const arr = [1, 2, 3];
const newArray = [...arr, 4, 5];

console.log(newArray);
NeNaD
  • 18,172
  • 8
  • 47
  • 89
1

You can use concat for that.

The concat() method will join two (or more) arrays and will not change the existing arrays, but instead will return a new array, containing the values of the joined arrays.

const arr = [1, 2, 3];
const newArray = arr.concat([4, 5]);

console.log(newArray)

Another option is to use spread syntax (...) (introduced in ES6)

const arr = [1, 2, 3];
const newArray = [...arr, ...[4, 5]];

console.log(newArray) 
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • 1
    There is no destructuring in the second code. It's just spread syntax. – VLAZ May 28 '21 at 12:30
  • 1
    `Array.prototype.concat` was introduced in ES3, a long time before ES5. – Bergi May 28 '21 at 12:34
  • 1
    @RanTurner VLAZ wrote spread *syntax*. [It's not an operator](https://stackoverflow.com/q/44934828/1048572) (or otherwise the OP's code might have worked) – Bergi May 28 '21 at 12:35