JS Array Concat() Explained

Mr A
Mr A
May 31 · 2 min read

step by step…

Concatenate

JS Array Concat

We use concat to add values to an array.

let arr = [1, 2]
let arr2 = arr.concat(3)
console.log(arr2)[1, 2, 3]

Concat creates a shallow copy of an existing array that includes arguments you pass to it.

Let’s confirm that the new array is a shallow copy:

console.log(arr2 !== arr) true

We can supply more than one argument and use a variety of different types:

let arr3 = arr.concat(3, 'string', undefined)
console.log(arr3)[1, 2, 3, 'string', undefined]

Accepting other arrays as arguments

When concat encounters an array as one of the arguments it will push all the values into the new array.

let arr4 = arr.concat([3, 4, 5, 6])
console.log(arr4)[1, 2, 3, 4, 5, 6]

This also works with multiple arrays and values as arguments:

let arr5 = arr.concat([3], [4], 5)
console.log(arr5) [1, 2, 3, 4, 5]

However, this will not work for nested arrays as concat only flattens arrays one level deep:

let arr6 = arr.concat([3], [4, [5, 6]])
console.log(arr6)[1, 2, 3, 4, [5, 6]]

Merging two arrays example

We have two variables that represent stock exchanges that will hold stock’s name and price:

let nasdaq = [
  {
    name: 'GOOGL',
    price: 1107.19
  },
  {
    name: 'TSLA',
    price: 184.99
  },
]let nyse = [
  {
    name: 'IBM',
    price: 127.04
  },
  {
    name: 'VS',
    price: 54.32
  },
]

Let’s print all the stock names for nasdaq using the forEach method:

nasdaq.forEach(stock => console.log(stock.name))GOOGL
TSLA

What if we also want to print the stock names for nyse?

Instead of using another forEach we can use concat to combine the arrays together:

let combined = nasdaq.concat(nyse)console.log(combined)[ 
  { name: 'GOOGL', price: 1107.19 },  
  { name: 'TSLA', price: 184.99 },
  { name: 'IBM', price: 127.04 },
  { name: 'VS', price: 54.32 }
]

Then use forEach to print out the stock names.

combined
  .forEach(stock => console.log(stock.name))GOOGL
TSLA
IBM
VS

Chain concat with other array methods

A better way is to use method chaining. We can use concat to merge the two arrays and then use forEach on the returned array:

nasdaq
  .concat(nyse)
  .forEach(stock => console.log(stock.name))GOOGL
TSLA
IBM
VS

And that’s it.

If you enjoyed this article, please check out my other article where you will learn how to Build JavaScript’s Array Concat

Thanks for reading : )

Mr A

Written by

Mr A

Sharing what I know with the rest of the world…