Created
December 27, 2021 06:28
-
-
Save hoyangtsai/09faeb4e2885b9df80ec92c6f71c60d8 to your computer and use it in GitHub Desktop.
Duplicate an array (make a copy, not reference)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code from William Vincent blog, JavaScript: Duplicate an Array