Create new array without impacting values from old array in JavaScript?

Let’s say the following is our current array −

var listOfNames=["John","Mike","Sam","Carol"];

Use JSON.parse(JSON.stringify()) to create new array and set values from the old array above.


function createNewArray(listOfNames) {
   return JSON.parse(JSON.stringify(listOfNames));
var listOfNames=["John","Mike","Sam","Carol"];
var namesArray = listOfNames.slice();
console.log("The new Array=");

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo111.js.


This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo111.js
The new Array=
[ 'John', 'Mike', 'Sam', 'Carol' ]