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

JavascriptWeb DevelopmentObject Oriented Programming

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.

Example

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

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

node fileName.js.

Here, my file name is demo111.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo111.js
The new Array=
[ 'John', 'Mike', 'Sam', 'Carol' ]
raja
Published on 09-Sep-2020 16:35:27
Advertisements