I have a function that receives 2 arguments:
- A list of books (bookList).
- The book to delete from that list (book)
But after the function I want to keep the original list (bookList) intact so I "copy" it by creating another variable to a new list (newlibrary)
var bookList = [
"The Hound of the Baskervilles",
"On The Electrodynamics of Moving Bodies",
"Philosophiæ Naturalis Principia Mathematica",
"Disquisitiones Arithmeticae"
];
function remove( library, book ) {
var newlibrary = library;
newlibrary.splice( newlibrary.indexOf( book ), 1 );
return newlibrary;
}
console.log( 'Antes:', bookList );
remove( bookList, 'On The Electrodynamics of Moving Bodies' );
console.log( 'Después:', bookList );
The function returns newlibrary with the list and the book correctly deleted, but nevertheless if I later call the original list bookList it turns out that the book has also been deleted there:
Before: [
"The Hound of the Baskervilles",
"On The Electrodynamics of Moving Bodies",
"Philosophiæ Naturalis Principia Mathematica",
"Disquisitiones Arithmeticae"
]
After: [
"The Hound of the Baskervilles",
"Philosophiæ Naturalis Principia Mathematica",
"Disquisitiones Arithmeticae"
]
Conclusion, both lists have now been modified, when I just wanted to modify the newly created one and leave the first one intact.
What am I doing wrong ?
Because, in JavaScript, objects and arrays are used by references . That means that you have several references to the same object .
With that, you have 2 references ; two variables that actually point to the same object in memory. This behavior only applies to objects , arrays , and functions . Does not apply for primitive types :
To do what you want, you have to create a deep copy of your array , and modify the copy . There are several alternatives, but my preference, due to its simplicity, is to use
JSON.parse( JSON.stringify( ) );
:You have to be careful with these types of copies; for instance:
That is, not all objects can be deep copied ; As in the example, we can find recursive data that is simply impossible to duplicate.
Note ( Thanks to user JackNavaRow ). To get similar results, without worrying about making deep copies of the
Object
u 'sArray
involved ourselves, we can use external libraries, such asimmutable-js
. So we can treat all our objects as values instead of references .This is because the splice function modifies the original array, as stated in the documentation.
array.splice
If you want to just get a copy of the array without the elements you can use slice.
array.slice