How do I remove an element from an array by index in JavaScript?
Ava W
ava w profile pic

To remove an element from an array by its index in JavaScript, you can use various methods depending on your requirements. Here are a few approaches: 1. Using thesplice() method: - Thesplice() method allows you to modify an array by adding or removing elements. By specifying the index and the number of elements to remove, you can delete an element at a specific index.

1
2
3
4
5
6
7
8
9
10

   const fruits = ["apple", "banana", "orange", "grape"];

   function removeElementByIndex(arr, index) {
     arr.splice(index, 1);
     return arr;
   }

   console.log(removeElementByIndex(fruits, 1)); // Output: ["apple", "orange", "grape"]
   

2. Creating a new array: - If you prefer to keep the original array unchanged, you can create a new array by excluding the element at the specified index.

1
2
3
4
5
6
7
8
9

   const fruits = ["apple", "banana", "orange", "grape"];

   function removeElementByIndex(arr, index) {
     return arr.filter((_, i) => i !== index);
   }

   console.log(removeElementByIndex(fruits, 1)); // Output: ["apple", "orange", "grape"]
   

3. Using theslice() method: - Theslice() method can be used to extract a portion of an array. You can combine it with the spread operator (...) to create a new array excluding the element at the given index.

1
2
3
4
5
6
7
8
9

   const fruits = ["apple", "banana", "orange", "grape"];

   function removeElementByIndex(arr, index) {
     return [...arr.slice(0, index), ...arr.slice(index + 1)];
   }

   console.log(removeElementByIndex(fruits, 1)); // Output: ["apple", "orange", "grape"]
   

4. Using thefilter() method: - Thefilter() method creates a new array with elements that pass a certain condition. By filtering out the element at the specified index, you can achieve the removal.

1
2
3
4
5
6
7
8
9

   const fruits = ["apple", "banana", "orange", "grape"];

   function removeElementByIndex(arr, index) {
     return arr.filter((_, i) => i !== index);
   }

   console.log(removeElementByIndex(fruits, 1)); // Output: ["apple", "orange", "grape"]
   

These are just a few examples of how you can remove an element from an array by its index in JavaScript. The method you choose depends on your specific use case, whether you want to modify the original array or create a new one, and the desired approach for handling the removal.