Skip to content

Instantly share code, notes, and snippets.

@hamannjames
Last active August 9, 2017 00:53
Show Gist options
  • Save hamannjames/d5113200042111c046ed9615e0a617b3 to your computer and use it in GitHub Desktop.
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.
// 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