{

Learn javascript Array concat method with example


This blog post covers how to combine/join/merge arrays in javascript with the inbuilt concat method.
Learn javascript Array concat method with example You can also check other posts on Javascript Add,Delete from Array

Array concat method

the method is used to join or concatenate one or more arrays and returns the final array. This method returns a new array not modifying the existing array.

the new array contains the merge of new arrays by order of elements in an array

Syntax

  
thisarray.concat(List of arrays)  

Parameters are a list of arrays ie zero or more arrays.
The output is returned to a new array.

Merge arrays using Concat Example

It is an example of merging arrays using ES5 using Array.concat

  
var arrayone = ['one', 'two', 'three'];  
var arraytwo = ['four', 'five', 'six'];  
console.log(arrayone.concat(arraytwo));  
// ['one', 'two', 'three','four', 'five', 'six'];  

How to merge/join two or more arrays in javascript

It is an example of merging the arrays without omitting duplicate values. array Concat method takes one or more arrays and joins with the original array and returns the new array. Original Array is not modified There is no inbuilt function to remove duplicate elements. You can iterate the array and do the manipulation to remove duplicates.

  
  
var one = ["id","1","name","kiran"]  
var two = ["id", "2", "name", "john"]  
var three = ["id","1","name","kiran"]  
  
var result = one.concat(two,three)  
console.log(result);  
// ["id","1","name","kiran","id", "2", "name", "john","id","1","name","kiran"];  

The same can be done using ES6 array destructing using spread Operator.

const result = [...one, ...two,...three];  

Or you can also Lodash or underscore utility libraries to do the same with third-party libraries

Nested array Concat example

nested arrays are arrays within the array that can be combined using the concat method

var one = ["id","1","name","kiran","a1",["newname","newkiran"]]  
var two = ["id", "2", "name", "john"]  
var three = ["id","1","name","kiran"]  
  
var result = one.concat(two,three)  
console.log(result);  
// ["id","1","name","kiran","a1",["newname","newkiran"],"id", "2", "name", "john","id","1","name","kiran"];  

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.