Skip to content

Instantly share code, notes, and snippets.

@hoyangtsai
Created December 27, 2021 06:28
Show Gist options
  • Save hoyangtsai/09faeb4e2885b9df80ec92c6f71c60d8 to your computer and use it in GitHub Desktop.
Save hoyangtsai/09faeb4e2885b9df80ec92c6f71c60d8 to your computer and use it in GitHub Desktop.
Duplicate an array (make a copy, not reference)
const arr = [1,2,3,4,5];
// Spread Operator
const arr1 = [...arr];
// Slice Operator
const arr2 = arr.slice();
// Concat
const arr3 = [].concat(arr)
// Array.from()
const arr4 = Array.from(arr);
// For loop
function arr5(arr) {
let newArr = [];
for(let i=0; i<arr.length; ++i) {
newArr[i] = arr[i];
}
return arr;
}
// Deep copy
const dupArray = JSON.parse(JSON.stringify(arr))
@hoyangtsai
Copy link
Author

This code from William Vincent blog, JavaScript: Duplicate an Array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment