masanos note

Array.prototype.concat()

2019-03-05
icon

"concat()" to combine two arrays into one.

Target Array

const arr1 = ['a', 'b', 'c']
const arr2 = ['d', 'e', 'f']
const arr3 = [0, 1]
const arr4 = [null]
const arr5 = [undefined]

Basic usage

console.log(arr1.concat(arr2))
>  ["a","b","c","d","e","f"]

console.log(arr1.concat(arr3))
> ["a","b","c",0,1]

console.log(arr1.concat(arr4))
> ["a","b","c",null]

console.log(arr1.concat(arr5))
> ["a","b","c",undefined]

console.log(arr1.concat(arr1))
> ["a","b","c","a","b","c"]

The existing array is not changed, but a new array is created.

console.log(arr1)
> ["a","b","c"]

arr1.concat(arr2)
console.log(arr1)
> ["a","b","c"]

Combine two or more arrays into one

console.log(arr1.concat(arr2, arr3, arr4))
> ["a","b","c","d","e","f",0,1,null]

Spread syntax (...)

It can also be written in a different way, like this.

console.log([...arr1, ...arr2])
> ["a","b","c","d","e","f"]

Ref.

https://codepen.io/masanos/pen/MWBBGNx
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

A record of the development is left in a web note.
Masanos
I want to make the world I see happy. Little by little, I am preparing to start a business. Thank you for your support.
Buy Me A Coffee
Copyright© masanos All Rights Reserved.