Skip to content

Instantly share code, notes, and snippets.

@Quaese
Last active October 24, 2018 10:02
Show Gist options
  • Save Quaese/e6c051eef1e5ad30d15b to your computer and use it in GitHub Desktop.
Save Quaese/e6c051eef1e5ad30d15b to your computer and use it in GitHub Desktop.
Deep Copy of an Array (and Object -> Method 4)
// METHODE 1
Array.prototype.slice.call([array])
/*
* Example
var arr = [37, 1, 2, 3],
arr2 = Array.prototype.slice.call(arr);
console.log(arr === arr2); // false => not equal
*/
// METHODE 2: Prototype:
Array.prototype.deepCopy = function() {
return Array.prototype.slice.call(this);
};
/*
* Example
var arr = [37, 1, 2, 3],
arr2 = arr.deepCopy;
console.log(arr === arr2); // false => not equal
*/
// METHODE 3: Spread Operator (ES2015)
var arr = [1, 2, 3],
arr2 = [...arr];
arr === arr2; // => false
// METHODE 4: JSON.stringify/JSON.parse
var arr = [{ x:{z:1} , y: 2}],
arr2 = JSON.parse(JSON.stringify(arr));
arr === arr2; // => false
// prototype
Array.prototype.copy = function() {
return JSON.parse(JSON.stringify(arr));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment