Javascript Array create from another Array

Introduction

There are two accessor functions that allow you create new arrays from existing arrays: concat() and splice().

concat() function puts together two or more arrays to create a new array.

splice() function creates a new array from a subset of an existing array.

concat() is called from an existing array and its argument is another existing array.

The argument is concatenated to the end of the array calling concat().

The following program demonstrates how concat() works:

let cisDept = ["Mike", "Clayton", "Terrill", "Danny", "Jennifer"]; 
let dmpDept = ["Raymond", "Cynthia", "Bryan"]; 
let itDiv = cis.concat(dmp); 
console.log(itDiv); /*from w w w.  ja  v a  2 s.co  m*/
itDiv = dmp.concat(cisDept); 
console.log(itDiv); 

The splice() function creates a new array from the contents of an existing array.

The arguments to the function are the starting position for taking the splice and the number of elements to take from the existing array.

Here is how the method works:

let itDiv = ["Mike","Clayton","Terrill","Raymond","Cynthia","Danny","Jennifer"]; 
let dmpDept = itDiv.splice(3,3); 
let cisDept = itDiv; 
console.log(dmpDept); // Raymond,Cynthia,Danny 
console.log(cisDept); // Mike,Clayton,Terrill,Jennifer 



PreviousNext

Related