Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Merging Arrays (Concatenating)

In programming languages, concatenation refers to the process of joining strings end-to-end.

For example, concatenating “snow” and “ball” yields “snowball”.

Similarly, concatenating arrays involves joining arrays end-to-end.

JavaScript Array concat()

The concat() method generates a new array by merging (concatenating) existing arrays.

Example (Merging Two Arrays)

const myGirls = [“Cecilie”“Lone”];
const myBoys = [“Emil”“Tobias”“Linus”];

const myChildren = myGirls.concat(myBoys);

Please note that the concat() method does not alter the existing arrays; it consistently returns a new array.

Moreover, the concat() method can accept any number of array arguments.

Example (Merging Three Arrays)

const arr1 = [“Cecilie”“Lone”];
const arr2 = [“Emil”“Tobias”“Linus”];
const arr3 = [“Robin”“Morgan”];
const myChildren = arr1.concat(arr2, arr3);

Additionally, the concat() method can accept strings as arguments.

 

Example (Merging an Array with Values)

const arr1 = [“Emil”“Tobias”“Linus”];
const myChildren = arr1.concat(“Peter”); 

Array copyWithin()

The copyWithin() method duplicates array elements to a different position within the same array.

Examples

Copy all elements from index 0 to index 2 within the array.

const fruits = [“Banana”“Orange”“Apple”“Mango”];
fruits.copyWithin(20);

Copy the elements from index 0 to index 2 into index 2 within the array.

const fruits = [“Banana”“Orange”“Apple”“Mango”“Kiwi”];
fruits.copyWithin(202);

Please be aware that the copyWithin() method overwrites existing values within the array.

Additionally, note that the copyWithin() method does not append items to the array, nor does it alter the length of the array.