.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.
concat()
to flatten arrays, but only one value deep 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 ] ]
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*/