Javascript Array concat()

Introduction

The concat() method can merge two or more arrays.

This method returns a new array rather than changes the existing arrays.

const new_array = old_array.concat([value1[, value2[, ...[, valueN]]]])

The following code concatenates two arrays:

const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];/*from   ww w.j av a  2  s .  co  m*/

letters.concat(numbers);
console.log(letters);// ['a', 'b', 'c', 1, 2, 3]

The following code concatenates three arrays:

const num1 = [1, 2, 3];/*w w w  .jav a 2s. c om*/
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

const numbers = num1.concat(num2, num3);
console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

The following code concatenates three values to an array:

const letters = ['a', 'b', 'c'];

const alphaNumeric = letters.concat(1, [2, 3]);

console.log(alphaNumeric); // ['a', 'b', 'c', 1, 2, 3]

The following code concatenates nested arrays.

It demonstrates retention of references:

const num1 = [[1]];/*  w ww  .  j  av a 2  s  .c  o  m*/
const num2 = [2, [3]];

const numbers = num1.concat(num2);
console.log(numbers);// [[1], 2, [3]]
num1[0].push(4);// modify the first element of num1
console.log(numbers);// [[1, 4], 2, [3]]



PreviousNext

Related