Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • 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:
CopyOnWriteArrayList toArray() method in Java
Next article icon

JavaScript Array toSpliced() Method

Last Updated : 16 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, Array.toSpliced() method is used to create a new array with some elements removed and/or replaced at a given index, without modifying the original array.

The difference between the new toSpliced() method and the old splice() method is that the new method creates a new array, keeping the original array unchanged, while the old method alters the original array.

Syntax:

array.toSpliced(start, deleteCount, item1, item2, ..., itemN)

Parameters:

  • start: zero-based index from which the array will start changing.
  • deleteCount: integer indicating the number of elements to remove from start.
  • item1, item2, ..., itemN: The elements to add to the array, beginning from start

Return value:

The return value is a new array that consists of all elements before start, item1, item2, …, itemN, and all elements after start + deleteCount.

Example 1: In the below example, the Array.toSpliced() method is used to copy a part of a given array without modifying it.

JavaScript
const numbers = [10, 20, 30, 40, 50];
const sliced = numbers.toSpliced(1, 3);
console.log("Old Array: ", numbers);
console.log("New Array: ", sliced);

Output:

Old Array: [10, 20, 30, 40, 50]
New Array: [10, 50]

Example 2: In the below code, the Array.toSpliced() method is used to insert a value at specified index in array.

JavaScript
const days = ["Mon", "Wed", "Thurs", "Fri"];
const day2 = days.toSpliced(1, 0, "Tue");
console.log("New Array", day2);
console.log("Old Array", days);  

Output:

New Array: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri']
Old Array: ['Mon', 'Wed', 'Thurs', 'Fri']

Example 3: In below code, the Array.toSpliced() method is used to delete the two words starting from index 2.

JavaScript
const words = 
    ["Apple", "Banana", "Cherry", 
    "Date", "Elderberry", "Fig"];
const result = words.toSpliced(2, 2);
console.log("New Array: ", result);
console.log("Old Array: ", words);

Output:

New Array: ['Apple', 'Banana', 'Elderberry', 'Fig']
Old Array: ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig']

Example 4: In the below code, the Array.toSpliced() method is used to replace the one at index 2 with two other items.

JavaScript
const items = 
    ["Chair", "Table", "Desk", "Sofa"];
const items2 = items.
    toSpliced(1, 1, "Bookshelf", "Lamp");
console.log("New Array: ", items2); 
console.log("Old Array: ", items);

Output:

New Array: ['Chair', 'Bookshelf', 'Lamp', 'Desk', 'Sofa']
Old Array: ['Chair', 'Table', 'Desk', 'Sofa']

Supported Browsers

  • Google Chrome
  • Edge
  • Internet Explorer 
  • Firefox
  • Opera
  • Safari

Next Article
CopyOnWriteArrayList toArray() method in Java

A

am8254s3a
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Methods

Similar Reads

    JavaScript Array splice() Method
    The splice() method in JavaScript is a powerful and flexible tool for modifying arrays. It allows us to add, remove, or replace elements within an array. It’s often used to update or manage array contents in various ways.Syntaxarray.splice(startIndex, deleteCount, item1, item2, ..., itemN);startInde
    4 min read
    JavaScript Array splice() Method
    The splice() method in JavaScript is a powerful and flexible tool for modifying arrays. It allows us to add, remove, or replace elements within an array. It’s often used to update or manage array contents in various ways.Syntaxarray.splice(startIndex, deleteCount, item1, item2, ..., itemN);startInde
    4 min read
    TypeScript Array splice() Method
    The Array.splice() is an inbuilt TypeScript function that changes the content of an array by adding new elements while removing old ones. It takes an index, a count of elements to remove, and optional elements to add, returning the removed elements and modifying the original array.Syntaxarray.splice
    3 min read
    ArrayList toArray() method in Java with Examples
    The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.Declaring toArray() methodpublic Object[] toArray() or public <T> T[] toArray(T[] a)Parameters: This method either accepts no parameters or it takes an array T[] as a para
    3 min read
    CopyOnWriteArrayList toArray() method in Java
    The toArray() method of CopyOnWriteArrayList is used to return an array containing all the elements in CopyOnWriteArrayList in the correct order. Syntax: public Object[] toArray() or public <T> T[] toArray(T[] a) Parameters: This method either accepts no parameters or it takes an array T[] a a
    2 min read
    CopyOnWriteArrayList toArray() method in Java
    The toArray() method of CopyOnWriteArrayList is used to return an array containing all the elements in CopyOnWriteArrayList in the correct order. Syntax: public Object[] toArray() or public <T> T[] toArray(T[] a) Parameters: This method either accepts no parameters or it takes an array T[] a a
    2 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
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