Thursday, 26 April 2018

Array.prototype.concat() - JavaScript

This method is used to merge two sorted arrays and returns a new array. This method does not affect the exisiting arrays.

The concat method creates a new array consisting of the elements in
the object which it is called, followed in order for each argument. It will return a shallow copy.
 Elements of the original arrays are copied into the new array as follows:

1. Object references (and not the actual object): concat copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays. This includes elements of array arguments that are also arrays.

2. Data types such as strings, numbers and booleans (not String, Number, and Boolean objects): concat copies the values of strings and numbers into the new array.

EXAMPLE:

var arr1 = ['Guru','Tegh','Bahadur'];
var arr2=['Institute','of','Technology'];

var result=arr1.concat(arr2);

console.log(result+"\n\n");


//Concating more than two arrays:

var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3=[7,8,9];
var arr4=[45,67];

var result=arr1.concat(arr2,arr4,arr3);
console.log(result+"\n\n");


//Concatenating nested arrays

var arr1=[['a']];
var arr2=['b','c','d'];
var arr3=['e',['f','g']];

var result=arr1.concat(arr2,arr3);

console.log("The output of the nested concatenation: \n");
for(var i=0;i<result.length;i++){
console.log(result[i]);
}


OUTPUT:






EmoticonEmoticon