menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:splice() Method

menu

In JavaScript, the splice() method is used to modify the contents of an array by removing or replacing existing elements and/or adding new elements at a specified position within the array. It is a powerful and versatile array manipulation method.

The splice() method can perform the following actions:

  1. Remove Elements:

    • You can remove elements from an array by specifying the starting index and the number of elements to remove.

  2. Replace Elements:

    • You can replace elements in an array by specifying the starting index, the number of elements to replace, and the new elements to insert.

  3. Add Elements:

    • You can add elements to an array by specifying the starting index as well as the elements to insert.

Here's the basic syntax of the splice() method:

javascriptarray.splice(start, deleteCount, item1, item2, ...);
  • array: The array on which you want to perform the operation.

  • start: The index at which to start modifying the array.

  • deleteCount: The number of elements to remove from the array (optional). If set to 0, no elements are removed.

  • item1, item2, ...: Elements to add to the array at the specified start index (optional).

The splice() method returns an array containing the removed elements, or an empty array if no elements were removed.

Here are some examples to illustrate how splice() works:

javascriptconst fruits = ['apple', 'banana', 'cherry', 'date'];

// Remove 'cherry' and 'date'
const removed = fruits.splice(2, 2);
console.log(fruits); // Outputs: ['apple', 'banana']
console.log(removed); // Outputs: ['cherry', 'date']

// Replace 'banana' with 'grape' and 'kiwi'
fruits.splice(1, 1, 'grape', 'kiwi');
console.log(fruits); // Outputs: ['apple', 'grape', 'kiwi']

// Add 'orange' and 'mango' at index 2
fruits.splice(2, 0, 'orange', 'mango');
console.log(fruits); // Outputs: ['apple', 'grape', 'orange', 'mango', 'kiwi']

In the examples above, splice() is used to perform various operations on the fruits array, including removal, replacement, and insertion of elements. It is a flexible method that allows you to manipulate arrays according to your specific needs.

1280 x 720 px