This article will show you how to remove item from given index in an array in JavaScript. There are several approaches to remove an item from a given index in an array in JavaScript, each with a description and complete code example are given below:
1. Using Array.splice() Method
Using the splice()
method to remove a specified number of items from a given index.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const indexToRemove = 1; const itemsToRemove = 1; array.splice(indexToRemove, itemsToRemove); // Output: [ 'Banana', 'Grapes', 'Mango' ] console.log(array);
2. Using Array.slice() Method
Using the slice()
method to create a new array without the item at the given index.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const indexToRemove = 1; const newArray = [ ...array.slice(0, indexToRemove), ...array.slice(indexToRemove + 1) ]; // Output: [ 'Banana', 'Grapes', 'Mango' ] console.log(newArray);
3. Using Array.filter() Method
Using the filter()
method to create a new array excluding the item at the given index.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const indexToRemove = 1; const newArray = array.filter((_, index) => index !== indexToRemove); // Output: [ 'Banana', 'Grapes', 'Mango' ] console.log(newArray);
4. Using Array.slice() with for Loop
Using the slice()
method along with a for
loop to create a new array without the item at the given index.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const indexToRemove = 1; const newArray = []; for (let i = 0; i < array.length; i++) { if (i !== indexToRemove) { newArray.push(array[i]); } } // Output: [ 'Banana', 'Grapes', 'Mango' ] console.log(newArray);
5. Using Array.slice() with Destructuring
Using slice()
along with array destructuring to create a new array without the item at the given index.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const indexToRemove = 1; const [ ...newArray] = [ ...array.slice(0, indexToRemove), ...array.slice(indexToRemove+1, array.length) ]; // Output: [ 'Banana', 'Grapes', 'Mango' ] console.log(newArray);
6. Using Array.splice() in a Function
Creating a function to encapsulate the logic of removing an item from a given index using splice()
.
function removeItemAt(indexToRemove, array) { array.splice(indexToRemove, 1); } const fruits = ['Banana', 'Orange', 'Grapes', 'Mango']; const indexToRemove = 1; removeItemAt(indexToRemove, fruits); // Output: [ 'Banana', 'Grapes', 'Mango' ] console.log(fruits);