- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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' ]
Advertisements