how to copy array in js code example

Example 1: javascript copy an array

let arr =["a","b","c"];
// ES6 way
const copy = [...arr];

// older method
const copy = Array.from(arr);

Example 2: copy array javascript

const sheeps = ['Apple', 'Banana', 'Juice'];

// Old way
const cloneSheeps = sheeps.slice();

// ES6 way
const cloneSheepsES6 = [...sheeps];

Example 3: js clone array

var clone = myArray.slice(0);

Example 4: javascript copy array

// this is for array with complex object
var countries = [
  {name: 'USA', population: '300M'}, 
  {name: 'China', population: '1.6B'}
];

var newCountries = JSON.parse(JSON.stringify(countries));

Example 5: javascript copy array

var oldColors=["red","green","blue"];
var newColors = oldColors.slice(); //make a clone/copy of oldColors

Example 6: how to copy one array to another in javascript

// 1) Array of literal-values (boolean, number, string) 
const type1 = [true, 1, "true"];

// 2) Array of literal-structures (array, object)
const type2 = [[], {}];

// 3) Array of prototype-objects (function)
const type3 = [function () {}, function () {}];

Tags:

Java Example