Notes

Array.concat

Edit on GitHub

JavaScript
2 minutes

.concat()

.concat() takes an existing array, adds a value to it and returns a new array

it takes a copy of the original array, adds to it any parameters passed and returns a new array.

.concat() is the equivalent of .push(), but superior, because it does not edit the data in place, it gives a new array as a result.

  • you can pass in multiple values
  • you can pass in different types
  • you can pass in other arrays as params. it gets every item in the array and adds it in the new array.
  • you can use concat() to flatten arrays, but only one value deep

Examples

adding items to arrays

 1let nums = [1, 2]
 2let newNums = nums.concat(3)
 3console.info(newNums) // [ 1, 2, 3 ]
 4
 5let moreNums = nums.concat(3, 4, 5)
 6console.info(moreNums) // [ 1, 2, 3, 4, 5 ]
 7
 8let diverseNums = nums.concat(true, 'hello', undefined)
 9console.info(diverseNums) // [ 1, 2, true, 'hello', undefined ]
10
11let addArr = nums.concat([ 3, 4 ], [ 5, [6, 7 ]])
12console.info(addArr) // [ 1, 2, 3, 4, 5, [ 6, 7 ] ]

log all names in 3 different arrays of objects

 1let people = [{name: 'Aamnah'}, {name: 'Ali'}]
 2let people2 = [{name: 'Alex'}, {name: 'Benny'}]
 3let people3 = [{name: 'Himesh'}, {name: 'Shareese'}, {name: 'Yaacov'}, {name: 'Martin'}]
 4
 5let names = people.concat(people2, people3).forEach(person => console.info(person.name))
 6
 7/*
 8Aamnah
 9Ali
10Alex
11Benny
12Himesh
13Shareese
14Yaacov
15Martin
16*/

Related