copy arrays javascript code example

Example 1: copy array javascript

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

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

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

Example 2: javascript duplicate an array

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

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

Example 3: javascript copy array

/* Copying arrays or parts of arrays in JavaScript */

var fruit = ["apple", "banana", "fig"]; // Define initial array.
console.log(fruit); // ["apple", "banana", "fig"]

// Copy an entire array using .slice()
var fruit2 = fruit.slice(); 
console.log(fruit2); // ["apple", "banana", "fig"]

// Copy only two array indicies rather than all three
// From index 0 (inclusive) to index 2 (noninclusive)
var fruit3 = fruit.slice(0,2); 
console.log(fruit3); // ["apple", "banana"]

Example 4: js copy part of array

// The slice function copies parts of an array and 
// do therefore not change the default array

let arr = ["apple", "kiwi", "banana", "pear"];

let newArray = arr.slice(1, 2)

console.log(newArray); // output : kiwi