JavaScript Array splice() Explained: Delete, Insert, Replace Elements (with Practical Examples)

目次

3. Practical Ways to Use splice() (with Code Examples)

In this section, we’ll walk through practical examples of using JavaScript’s splice() method. We’ll cover three common patterns—deleting, inserting, and replacing—and review key notes for each.

3.1 How to Delete Elements

With splice(), you can easily remove specific elements from an array.

Example 1: Delete a single element

let fruits = ["apple", "banana", "cherry", "date"];
fruits.splice(1, 1); // Deletes "banana"
console.log(fruits); // ["apple", "cherry", "date"]

Explanation:

  • Removes 1 element starting at index 1 (“banana”).

Example 2: Delete multiple elements

let fruits = ["apple", "banana", "cherry", "date"];
fruits.splice(1, 2); // Deletes "banana" and "cherry"
console.log(fruits); // ["apple", "date"]

Explanation:

  • Removes 2 elements starting at index 1 (“banana” and “cherry”).

Note:
Because removed elements are excluded from the array, the original array is changed (this is a destructive method).

3.2 How to Insert Elements

With splice(), you can insert new elements at a specific position.

Example 1: Insert one element

let colors = ["red", "blue"];
colors.splice(1, 0, "green"); // Inserts "green" at index 1
console.log(colors); // ["red", "green", "blue"]

Explanation:

  • Setting the second argument to 0 lets you insert without deleting anything.

Example 2: Insert multiple elements

let colors = ["red", "blue"];
colors.splice(1, 0, "green", "yellow"); // Inserts multiple elements
console.log(colors); // ["red", "green", "yellow", "blue"]

Note:
There’s no strict limit on the insertion position or number of elements—insert as many as you need.

3.3 How to Replace Elements

You can also replace existing elements using splice().

Example 1: Replace a single element

let numbers = [1, 2, 3, 4];
numbers.splice(1, 1, 5); // Replaces "2" at index 1 with "5"
console.log(numbers); // [1, 5, 3, 4]

Explanation:

  • Deletes 1 element starting at index 1, then inserts 5 at the same position.

Example 2: Replace multiple elements

let numbers = [1, 2, 3, 4];
numbers.splice(1, 2, 5, 6); // Replaces "2" and "3" with "5" and "6"
console.log(numbers); // [1, 5, 6, 4]

Explanation:

  • Deletes 2 elements starting at index 1, then inserts 5 and 6.

4. Advanced Use Cases of splice(): Practical Scenarios

Here are practical scenarios where splice() can be especially useful—such as managing form data, editing table rows, and preprocessing datasets.

4.1 Example: Manipulating Form Data

Managing dynamic form fields

When building a dynamic form where users can add or remove fields, splice() is extremely handy.

Example: Adding and removing fields

let formData = ["Name", "Email", "Phone"];

// Insert a field
formData.splice(2, 0, "Address");
console.log(formData); // ["Name", "Email", "Address", "Phone"]

// Remove a field
formData.splice(1, 1);
console.log(formData); // ["Name", "Address", "Phone"]

Explanation:

  • For inserting, we add “Address” at index 2.
  • For deleting, we remove “Email” at index 1 and the remaining elements shift automatically.

This is useful when you need to dynamically modify fields based on user actions.

4.2 Adding and Removing Dynamic Table Rows

In web applications, table-style data management is common. Here’s an example of inserting and deleting table rows.

Example: Adding and removing rows

let tableData = [
  ["ID", "Name", "Age"],
  [1, "Tanaka", 25],
  [2, "Sato", 30]
];

// Insert a new row
tableData.splice(2, 0, [3, "Takahashi", 28]);
console.log(tableData);
// [["ID", "Name", "Age"], [1, "Tanaka", 25], [3, "Takahashi", 28], [2, "Sato", 30]]

// Delete a row
tableData.splice(1, 1);
console.log(tableData);
// [["ID", "Name", "Age"], [3, "Takahashi", 28], [2, "Sato", 30]]

Explanation:

  • For inserting, we add a new data row at index 2.
  • For deleting, we remove the row at index 1 (Tanaka).

This demonstrates flexible manipulation of table-like data structures.

4.3 Dataset Preprocessing and Editing

When handling large datasets, you may need to edit or replace specific records. Here’s an example of replacing part of a dataset.

Example: Updating a dataset

let users = [
  { id: 1, name: "Tanaka", age: 25 },
  { id: 2, name: "Sato", age: 30 },
  { id: 3, name: "Takahashi", age: 28 }
];

// Update an entry
users.splice(1, 1, { id: 2, name: "Yamada", age: 32 });
console.log(users);
// [{ id: 1, name: "Tanaka", age: 25 }, { id: 2, name: "Yamada", age: 32 }, { id: 3, name: "Takahashi", age: 28 }]

Explanation:

  • Deletes the record at index 1 and replaces it with a new object.
  • Even object-based data can be edited smoothly with splice().

5. splice() vs slice(): Key Differences and When to Use Each (With a Comparison Table)

In JavaScript, splice and slice are commonly used methods for working with arrays. Because their names look similar, it’s easy to confuse them—but their behavior and use cases are very different. In this section, we’ll compare splice() and slice() and explain how to choose the right one.

5.1 The Core Difference Between splice() and slice()

MethodWhat it doesMutates the original array?Common use cases
spliceInsert / delete / replace elementsYesEdit part of an array or insert new elements
sliceExtract a portion of an arrayNoCopy a range of elements into a new array

5.2 splice() Examples and Characteristics

Characteristics:

  • It mutates the original array (a destructive method).
  • You can insert, delete, and replace elements.

Example 1: Editing elements with splice()

let fruits = ["apple", "banana", "cherry", "date"];
fruits.splice(1, 2, "orange", "grape"); // Removes "banana" and "cherry", then inserts new elements
console.log(fruits); // ["apple", "orange", "grape", "date"]

Explanation:

  • Deletes 2 elements starting at index 1, then inserts “orange” and “grape”.
  • The key point is that the original array is modified directly.

5.3 slice() Examples and Characteristics

Characteristics:

  • The original array does not change (a non-destructive method).
  • Used to extract elements into a new array.

Example 1: Extracting a portion with slice()

let fruits = ["apple", "banana", "cherry", "date"];
let result = fruits.slice(1, 3); // Extracts elements from index 1 up to (but not including) 3
console.log(result); // ["banana", "cherry"]
console.log(fruits); // ["apple", "banana", "cherry", "date"]

Explanation:

  • Elements in the range [1, 3) are returned as a new array.
  • The original array remains unchanged.

5.4 How to Choose Between splice() and slice()

1. Use splice() when you want to modify the array

Example: Removing an unnecessary item from a list

let tasks = ["task1", "task2", "task3"];
tasks.splice(1, 1); // Removes the item at index 1
console.log(tasks); // ["task1", "task3"]

2. Use slice() when you want a subset without changing the original array

Example: Saving only part of an array separately

let data = [10, 20, 30, 40, 50];
let subset = data.slice(1, 4); // Extracts elements from index 1 up to 4 (exclusive)
console.log(subset); // [20, 30, 40]
console.log(data); // [10, 20, 30, 40, 50] (unchanged)

5.5 Practical Code Example: splice() vs slice()

The following code helps you see the difference between splice and slice more clearly.

let items = ["A", "B", "C", "D", "E"];

// splice: destructive (mutates the original array)
let removed = items.splice(1, 2); // Removes "B" and "C"
console.log(items); // ["A", "D", "E"]
console.log(removed); // ["B", "C"]

// slice: non-destructive (does not mutate the original array)
let extracted = items.slice(0, 2); // Extracts elements from index 0 up to 2 (exclusive)
console.log(items); // ["A", "D", "E"] (unchanged)
console.log(extracted); // ["A", "D"]

Key points:

  • splice directly edits the original array, and returns the removed elements.
  • slice keeps the original array intact and returns a new array.

6. splice() vs split(): Avoid Confusing Array Editing with String Splitting

JavaScript provides many methods for working with arrays and strings. Among them, split() looks similar to splice(), so they’re often confused—but they do completely different things. In this section, we’ll clarify the differences between split() and splice() to help you avoid common mistakes.

6.1 What Is split()?

split() is a string method that splits a string using a delimiter and returns an array.

Basic Syntax

string.split(separator, limit);

Parameter Details

  1. separator (Required):
  • A delimiter string or a regular expression used to split the string.
  1. limit (Optional):
  • The maximum number of elements to include in the returned array.

6.2 split() Examples

Example 1: Split a comma-separated string

let text = "apple,banana,cherry,date";
let result = text.split(","); // delimiter is ","
console.log(result); // ["apple", "banana", "cherry", "date"]

Example 2: Split a string by spaces

let sentence = "Hello World JavaScript";
let words = sentence.split(" "); // delimiter is a space
console.log(words); // ["Hello", "World", "JavaScript"]

Example 3: Split using a regular expression

let data = "2024/12/31";
let parts = data.split(/[-/]/); // split by "-" or "/"
console.log(parts); // ["2024", "12", "31"]

6.3 Key Differences Between splice() and split()

Here’s a table comparing splice and split side by side.

MethodTargetWhat it doesResult typeMutates the original data?
spliceArrayInsert / delete / replace elementsMutates the original arrayYes
splitStringSplits a string into an array by delimiterReturns a new arrayNo

6.4 When to Use splice() vs split()

1. Use splice() when you want to edit an array

Example: Remove an unnecessary item from an array

let colors = ["red", "blue", "green"];
colors.splice(1, 1); // Removes the element at index 1
console.log(colors); // ["red", "green"]

2. Use split() when you want to convert a string into an array

Example: Split a sentence into words

let sentence = "I love JavaScript";
let words = sentence.split(" ");
console.log(words); // ["I", "love", "JavaScript"]

6.5 Combining split() and splice(): A Practical Example

Here’s a useful pattern: split a string into an array, then edit the array with splice().

Example: Split string data and then edit it

let data = "apple,banana,cherry,date";

// 1. Use split() to convert the string into an array
let fruits = data.split(","); // ["apple", "banana", "cherry", "date"]

// 2. Use splice() to edit the array
fruits.splice(2, 1, "grape"); // Replaces "cherry" with "grape"
console.log(fruits); // ["apple", "banana", "grape", "date"]

Key points:

  • split converts a string into an array so it’s easier to work with.
  • splice performs the needed edits (insert / delete / replace) on the array.

7. Important Notes When Using splice()

JavaScript’s splice() method is powerful, but depending on how you use it, it can cause unexpected behavior, errors, or performance issues. In this section, we’ll cover key cautions and best practices to help you use splice() safely and effectively.

7.1 Be Careful: splice() Mutates the Original Array

Problem: Risk of data loss due to destructive behavior

splice() modifies the original array directly. If you want to preserve the original data, you may accidentally lose it.

Example: The original array gets changed

let numbers = [1, 2, 3, 4];
let removed = numbers.splice(1, 2); // Removes 2 elements starting at index 1
console.log(numbers); // [1, 4] (original array is changed)
console.log(removed); // [2, 3] (removed elements)

Solution: Copy the array before editing

let numbers = [1, 2, 3, 4];
let copy = [...numbers]; // Copy the array
copy.splice(1, 2); // Edit the copy
console.log(numbers); // [1, 2, 3, 4] (original array is unchanged)
console.log(copy); // [1, 4]

7.2 Watch Out for Performance Issues

Problem: Heavy cost when editing large arrays

splice() can trigger element shifting and re-indexing when inserting or removing items. With large arrays, this may become slow.

Example: Editing a large array

let bigArray = Array(1000000).fill(0);
console.time("splice");
bigArray.splice(500000, 1); // Removes one element in the middle
console.timeEnd("splice"); // Measure execution time

Solution: Use batch processing or alternative approaches

  • Split the array and process smaller chunks.
  • Consider non-destructive methods like slice() or concat() when appropriate.

7.3 Prevent Errors Caused by Wrong Index Values

Problem: Out-of-range indexes can lead to unexpected behavior

With splice(), specifying an out-of-range index does not throw an error. That can make bugs harder to notice.

Example: Out-of-range index

let items = ["A", "B", "C"];
items.splice(5, 1); // Out-of-range index
console.log(items); // ["A", "B", "C"] (no error occurs)

Solution: Validate the index before calling splice()

let items = ["A", "B", "C"];
let index = 5;

if (index < items.length) {
  items.splice(index, 1);
} else {
  console.log("The specified index is out of range.");
}

7.4 Use the Return Value (Removed Elements)

Key point: Removed elements are returned as an array

splice() returns the removed elements as an array. By using this return value, you can build more flexible logic.

Example: Store removed elements in another array

let tasks = ["task1", "task2", "task3"];
let removed = tasks.splice(1, 1); // Removes the element at index 1
console.log(removed); // ["task2"]

Practical use: Save deletion history

let history = [];
let tasks = ["task1", "task2", "task3"];

let removed = tasks.splice(1, 1);
history.push(...removed);

console.log(history); // ["task2"]

7.5 Avoid Mistakes by Combining splice() with Other Methods

  • Using map(): If you want to transform every element, use map() instead of splice().
  • Using filter(): If you want to extract elements based on a condition, use filter() instead of splice().

Example: Extract only elements that match a condition

let numbers = [10, 20, 30, 40, 50];
let filtered = numbers.filter(num => num > 20);
console.log(filtered); // [30, 40, 50]

8. Summary: Key Points for Mastering splice()

So far, we’ve covered JavaScript’s splice() method from the basics to advanced use cases and important cautions. In this section, we’ll review what you learned and organize the key takeaways you can apply in real projects.

8.1 Quick Recap of splice() Basics

  • Purpose: A method that can delete, insert, and replace elements in an array.
  • Syntax:
  array.splice(start, deleteCount, item1, item2, ...);
  • Main features:
  1. Delete elements → Remove unnecessary data.
  2. Insert elements → Add new data at a specific position.
  3. Replace elements → Change existing data into different values.

Example: Core operations (delete / insert / replace)

let data = ["A", "B", "C", "D"];

// Delete
data.splice(1, 2); // ["A", "D"]

// Insert
data.splice(1, 0, "X", "Y"); // ["A", "X", "Y", "D"]

// Replace
data.splice(2, 1, "Z"); // ["A", "X", "Z", "D"]

This is why splice() is so useful—it lets you write array edits in a compact and readable way.

8.2 Reviewing Differences from Other Methods

  1. splice() vs slice()
  • splice(): Mutates the original array (destructive) → best for editing.
  • slice(): Does not mutate the original array (non-destructive) → best for extracting.
  1. splice() vs split()
  • splice(): A method for editing arrays.
  • split(): A method for splitting strings into arrays.

8.3 Summary of Practical Use Cases

  • Form data management: Add or remove fields to build dynamic forms.
  • Table data editing: Insert or delete rows for flexible table updates.
  • Data processing: Efficiently edit JSON or object-based datasets.

8.4 Best Practices and Key Cautions

  • Be careful with destructive edits: Since splice() mutates the original array, create a copy when needed.
  • Performance awareness: For large datasets, consider smaller operations or alternative methods.
  • Error prevention: Validate index ranges and add checks when necessary.
  • Use the return value: Track removed elements for logs or history.
  • Consider other methods: Use filter() or map() when they better fit your goal.

8.5 How to Keep Improving Your splice() Skills

1. Learn by writing real code

  • Try using splice() in everyday scenarios to build confidence through practice.

2. Learn related array methods together

  • filter: Extract elements that match a condition.
  • map: Transform every element in an array.
  • reduce: Aggregate values into a single result.

3. Use official documentation and trusted resources

  • Check MDN Web Docs for the latest updates.
  • Explore more examples and comparisons with other array methods.

Summary and Next Steps

In this article, we explained the following topics about JavaScript’s splice() method:

  1. Basic syntax and how parameters work
  2. Concrete examples for deleting, inserting, and replacing elements
  3. Differences vs other methods (slice, split) and how to choose
  4. Important cautions, error prevention, and performance tips

splice() is an extremely powerful tool for array manipulation in JavaScript. Once you can use it correctly, your code becomes much more efficient and flexible.

Next, try running the code examples from this article in your own environment. The more you practice, the more comfortable you’ll become with array editing, and that will directly improve your JavaScript skills.

9. Frequently Asked Questions (FAQ): Common Questions About splice()

Here are some of the most common questions and answers about JavaScript’s splice() method. These FAQs help beginners and intermediate developers clear up confusion and deepen their understanding.

Q1. Does splice() modify the original array?

A. Yes. splice() modifies the original array directly.
The splice() method is considered a destructive method because it changes the contents of the array after the operation.

Example:

let colors = ["red", "blue", "green"];
colors.splice(1, 1); // Removes the element at index 1
console.log(colors); // ["red", "green"]

Q2. What is the difference between splice() and slice()?

A. splice() mutates the original array, while slice() does not.

MethodEffect on the original arrayMain use cases
spliceMutates the original arrayDelete, insert, replace elements
sliceDoes not mutate the original arrayExtract elements / create a sub-array

Example: slice() is non-destructive

let colors = ["red", "blue", "green"];
let newColors = colors.slice(1, 2);
console.log(colors);    // ["red", "blue", "green"]
console.log(newColors); // ["blue"]

Q3. How do I add elements using splice()?

A. Set the second argument (deleteCount) to 0 to insert elements.

Example: Insert elements

let fruits = ["apple", "banana"];
fruits.splice(1, 0, "grape", "orange");
console.log(fruits); // ["apple", "grape", "orange", "banana"]

Q4. How can I remove the last element using splice()?

A. Use -1 as the start index, or calculate the last index using the array length.

Example:

let numbers = [1, 2, 3, 4];
numbers.splice(-1, 1);
console.log(numbers); // [1, 2, 3]

Q5. Can I search for an element and remove it with splice()?

A. Yes. Find the index first, then remove it with splice().

Example: Search by value and remove

let fruits = ["apple", "banana", "cherry"];
let index = fruits.indexOf("banana");
if (index !== -1) {
  fruits.splice(index, 1);
}
console.log(fruits); // ["apple", "cherry"]

Q6. What should I be careful about when using splice() with large datasets?

A. Be aware of performance costs, and consider processing in smaller chunks.

Example: Measuring performance

let bigArray = Array(100000).fill(0);
console.time("splice");
bigArray.splice(50000, 1000);
console.timeEnd("splice");

Q7. How do I replace multiple elements using splice()?

A. Pass multiple new items starting from the third argument.

Example: Replace multiple elements

let numbers = [1, 2, 3, 4];
numbers.splice(1, 2, 5, 6, 7);
console.log(numbers); // [1, 5, 6, 7, 4]

Summary

This FAQ section covered both basic and advanced questions about splice().

Main takeaways:

  • splice() mutates the original array, so use it carefully.
  • Understanding the differences between slice() and split() helps prevent confusion.
  • Consider performance and error prevention to write safer code.

Use these FAQs as a reference while you test code examples and deepen your understanding of splice().

10. Final Summary: Key Takeaways and Next Learning Steps

In this article, we provided a complete explanation of JavaScript’s splice() method. We covered everything from the basics to real-world use cases and frequently asked questions, so readers can fully understand how splice() works. This final section reviews the entire article and suggests what to learn next.

10.1 Key Points of splice()

  • splice() is a method used to delete, insert, and replace elements in an array.
  • Syntax:
  array.splice(start, deleteCount, item1, item2, ...);
  • Main use cases:
  • Deleting elements
  • Inserting elements
  • Replacing elements

10.2 Common Scenarios Where splice() Is Used

  • Managing form data: Great for adding or removing fields.
  • Dynamic table operations: Useful for inserting or deleting rows.
  • Data preprocessing: Helps edit JSON datasets and object-based records.

10.3 splice() Compared to Other Array Methods

  • splice() vs slice(): splice() mutates the original array, but slice() does not.
  • splice() vs split(): split() is for strings and creates arrays by splitting text.
  • splice() vs map() / filter(): Use map() and filter() for transformations and filtering, and use splice() for direct array edits.

10.4 Next Learning Steps

  1. Write practical code: Try the examples in this article and build a habit of coding regularly.
  2. Learn other array methods: Study map(), filter(), reduce(), and practice combining them with splice().
  3. Apply splice() in real projects: Use it for more advanced array manipulation in your own apps.
  4. Keep up with updates: Follow MDN and other official resources to learn new features and improvements.

10.5 Final Words

splice() is one of the most powerful and frequently used array methods in JavaScript. By applying what you learned in this article to real projects, you’ll strengthen your skills and become more efficient at handling data in JavaScript.

Mastering flexible array operations will significantly improve your productivity and confidence in JavaScript development.

広告