Sunday, November 11, 2018

Learn javascript Array concat method with example

This blog post covers how to combine/join/merge arrays in javascript with inbuilt concat method.
Learn javascript Array concat method with example

Array concat method


This method is used to join or concatenation the one or more arrays and returns the final array. This method returns new array not modifies the existing array.
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 array.
The output is returned a new array

Merge arrays using Concat Example 

This is an example for 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 

This is an example for merging the arrays without omitting duplicate values. array concat method takes one or more arrays and joins with original array and returns 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 array within the array which can be combined using 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"];

Related article


EmoticonEmoticon