-1

I need to merge multiple array values using JavaScript but as per my code its not working. I am explaining my code below.

let result = [];

let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];

result.concat(arr1);
result.concat(arr2);
result.concat(arr3);


console.log(result);

Here I am expecting output as [1,2,3,4,5,6] but as per my code its coming [].

Il Vic
  • 5,576
  • 4
  • 26
  • 37
subhraedqart
  • 115
  • 6
  • 3
    `concat` returns a new array, doesn't mutate the current one. – VLAZ May 19 '20 at 07:26
  • Please do some [basic research](https://www.google.com/search?q=javascript+concat+not+working+site:stackoverflow.com) before asking questions. This question has been asked many times before. – Ivar May 19 '20 at 07:28
  • 1
    If you're using es6, spread syntax is *really* easy. `const result = [ ...arr1, ...arr2, ...arr3 ]` – Joel Hager May 19 '20 at 07:29
  • @JoelHager or `result.push(...arr1); result.push(...arr2); result.push(...arr3);` – VLAZ May 19 '20 at 14:35
  • They do the same thing, but both use spread, and that way isn't very D.R.Y. Imo – Joel Hager May 19 '20 at 18:38

2 Answers2

0

Concat is a pure operator. It means it produces a new array instead of changing the one that is calling it.

let result = [];

let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];

result.concat(arr1); // returns an array
result.concat(arr2); // returns an array
result.concat(arr3); // returns an array

if you want to change a result array you can do it like this:

let result = [];

let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];

result = result.concat(arr1);
result = result.concat(arr2);
result = result.concat(arr3);

or

let result = [];

let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];

result.push(...arr1);
result.push(...arr2);
result.push(...arr3);

push is an impure operator so it is changing 'result' array. I am using a destructuring here to pass all of arr elements to push as separate arguments.

grzim
  • 534
  • 3
  • 10
-1

As @VLAZ suggested, you should store the returned array:

var a = [1, 2, 3];
var b = [4, 5, 6];
var c = a.concat(b);

console.log(c); // c is [1, 2, 3, 4, 5, 6]
Il Vic
  • 5,576
  • 4
  • 26
  • 37