Last active
August 9, 2017 00:53
-
-
Save hamannjames/d5113200042111c046ed9615e0a617b3 to your computer and use it in GitHub Desktop.
This little function deep clones an array, instead of slice which preserves references to objects and nested arrays.
This file contains 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
// Parts of this function were borrowed from http://blog.andrewray.me/how-to-clone-a-nested-array-in-javascript/ | |
// Link to code pen: https://codepen.io/jaspercreel/pen/jLmEWL | |
function trueClone(item) { | |
let copy, i; | |
if (Array.isArray(item)) { | |
copy = item.slice(0); | |
for (i = 0; i < copy.length; i++) { | |
copy[i] = trueClone(copy[i]); | |
} | |
return copy; | |
} | |
else if (typeof item === 'object') { | |
copy = Object.assign({}, item); | |
for (let prop in copy) { | |
copy[prop] = trueClone(copy[prop]); | |
} | |
return copy; | |
} | |
else { | |
return item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment