Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Find All Occurrence Indices in a JavaScript Array
Next article icon

How to clone an array in JavaScript ?

Last Updated : 09 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.

Here are some common use cases for cloning an array:

Table of Content

  • Using the Array.slice() Method
  • Using the spread Operator
  • Using the Array.from() Method
  • Using the Array.concat() Method
  • Using a for loop
  • Using the Array.map() Method
  • Using the Array.from() method with a map function
  • Using the Array.of() Method
  • Using the JSON.parse() and JSON.stringify() Methods
  • Using the Object.assign() Method
  • Using Array.reduce() Method
  • Using the Array.flatMap() Method
  • When to clone array?

Using the Array.slice() Method

We use the slice method to create a shallow copy of an array. This method creates a new array with a subset of the elements from the original array.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = originalArray.slice(); console.log(clonedArray);  

Output
[ 1, 2, 3 ] 

Using the spread Operator

Using the spread operator ... is a concise and easy way to clone an array in JavaScript. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = [...originalArray]; console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using the Array.from() Method

Using the Array.from() method is another way to clone an array in JavaScript. This method creates a new array from an existing array, using an optional mapping function to transform the values in the new array.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = Array.from(originalArray); console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using the Array.concat() Method

Using the Array.concat() method is another way to clone an array in JavaScript. This method creates a new array by concatenating two or more arrays together.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = [].concat(originalArray); console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using a for loop

This method involves iterating through each element in the original array and copying each element into a new array.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = []; for (let i = 0; i < originalArray.length; i++) {     clonedArray.push(originalArray[i]); } console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using the Array.map() Method

Using the Array.map() method is another way to clone an array in JavaScript. This method creates a new array by mapping each element from the original array to a new value.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = originalArray.map(x => x); console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using the Array.from() method with a map function

Using the Array.from() method with a map function is another way to clone an array in JavaScript. This method creates a new array by mapping each element from the original array to a new value using a provided function.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = Array.from(originalArray, x => x); console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using the Array.of() Method

This method creates a new array with the same elements as the original array.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = Array.of(...originalArray); console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using the JSON.parse() and JSON.stringify() Methods

Using the JSON.parse() and JSON.stringify() methods is another way to clone an array in JavaScript. This method involves converting the original array to a JSON string and then parsing the JSON string to create a new array.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = JSON.parse(JSON.stringify(originalArray)); console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using the Object.assign() Method

Using the Object.assign() method is another way to clone an array in JavaScript. This method creates a new array by copying the properties of the original array to a new object.

Example: This example shows the implementation of the above-explained approach.

JavaScript
const originalArray = [1, 2, 3]; const clonedArray = Object.assign([], originalArray); console.log(clonedArray); 

Output
[ 1, 2, 3 ] 

Using Array.reduce() Method

The Array.reduce() method executes a reducer function on each element of the array, resulting in a single output value. We can use it to construct a new array with the same elements as the original array.

Syntax:

array.reduce((accumulator, currentValue, currentIndex, array) => { ... }, initialValue);

Example: In this example, we'll use the Array.reduce() method to create a clone of an array.

JavaScript
// Input array const originalArray = [1, 2, 3, 4];  // Cloning the array using reduce const clonedArray = originalArray.reduce((acc, val) => {   acc.push(val);   return acc; }, []);  // Display the original and cloned arrays console.log("Original Array:", originalArray); // Output: [1, 2, 3, 4] console.log("Cloned Array:", clonedArray); // Output: [1, 2, 3, 4] 

Output
Original Array: [ 1, 2, 3, 4 ] Cloned Array: [ 1, 2, 3, 4 ] 

Note: Thus, When cloning an array, it is important to consider the complexity of the data and the performance requirements of the application.

Using the Array.flatMap() Method

Another approach to clone an array in JavaScript is by using the flatMap() method. The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. While its primary use case is for flattening arrays, it can also be utilized to clone an array by simply mapping each element to itself.

Example: In this example, we will use the flatMap() method to clone an array by mapping each element to itself.

JavaScript
const originalArray = [1, 2, 3, 4, 5];  const clonedArray = originalArray.flatMap(element => [element]);  console.log(clonedArray); console.log(originalArray === clonedArray); 

Output
[ 1, 2, 3, 4, 5 ] false 

When to clone array?

If you want to perform some operations on an array, such as sorting, filtering, or mapping, but you don't want to modify the original array, you can create a clone of the original array and perform the operations on the clone instead.

  • When passing an array to a function as an argument, you may want to ensure that the function does not modify the original array. In this case, you can pass a clone of the array instead.
  • If you want to preserve the original array for future reference, you can create a clone of the original array and use the clone for further processing or manipulation.
  • If you have an array that contains objects or arrays as elements, and you want to avoid modifying the original objects or arrays, you can create a clone of the array to work with, so that changes to the objects or arrays in the clone do not affect the original objects or arrays.

Thus, cloning an array in JavaScript is a useful technique for working with arrays in a way that preserves the integrity of the original array and its elements.


Next Article
Find All Occurrence Indices in a JavaScript Array
author
gupta19esha
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • JavaScript-DSA
  • JavaScript-Questions

Similar Reads

  • How to Add Elements to a JavaScript Array?
    Here are different ways to add elements to an array in JavaScript. 1. Using push() MethodThe push() method adds one or more elements to the end of an array and returns the new length of the array. Syntax array.push( element1, element2, . . ., elementN );[GFGTABS] JavaScript const arr = [10, 20, 30,
    3 min read
  • Create an Array of Given Size in JavaScript
    The basic method to create an array is by using the Array constructor. We can initialize an array of certain length just by passing a single integer argument to the JavaScript array constructor. This will create an array of the given size with undefined values. Syntax cosnt arr = new Array( length )
    4 min read
  • Insert at the Beginning of an Array in JavaScript
    Following are different ways to add new elements at the beginning of an array 1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
    2 min read
  • Remove Elements From a JavaScript Array
    Here are the various methods to remove elements from a JavaScript Array 1. Using pop() methodThe pop() method removes and returns the last element of an array. This function decreases the length of the array by 1 every time the element is removed. [GFGTABS] javascript let a = ["Apple",
    6 min read
  • Remove Duplicate Elements from JavaScript Array
    To Remove the elements from an array we can use the JavaScript set method. Removing duplicate elements requires checking if the element is present more than one time in the array. 1. Using JavaScript Set() - Mostly UsedThe JavaScript Set() method creates an object containing only unique values. To r
    3 min read
  • How to Remove Multiple Elements from Array in JavaScript?
    Here are various methods to remove multiple elements from an array in JavaScript 1. Using filter() MethodThe filter() method creates a new array with the elements that pass the condition. This method does not change the original array. [GFGTABS] JavaScript let a = [1, 2, 3, 4, 5]; let remove = [2, 4
    4 min read
  • Insert at the Beginning of an Array in JavaScript
    Following are different ways to add new elements at the beginning of an array 1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
    2 min read
  • Reverse an Array in JavaScript
    Here are the different methods to reverse an array in JavaScript 1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array. [GFGTABS] JavaScript let
    3 min read
  • JavaScript - Delete last Occurrence from JS Array
    These are the following ways to remove the last Item from the given array: 1. Using pop() Method (Simple and Easiest Method for Any Array) The pop() method is used to get the last element of the given array it can also be used to remove the last element from the given array. [GFGTABS] JavaScript let
    2 min read
  • Remove Empty Elements from an Array in JavaScript
    Here are different approaches to remove empty elements from an Array in JavaScript. 1. Using array.filter() MethodThe array filter() method is used to create a new array from a given array consisting of elements that satisfy given conditions. array.filter( callback( element, index, arr ), thisValue
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences