How can I remove a specific item from an array in JavaScript?
There are numerous techniques in JavaScript for removing a specific item from an array. The method you use is determined by your preferences as well as the specific needs of your project.
Here are some common approaches:
Using the splice() function to remove an item from an array:
You may use the splice() method to remove an item from an array by specifying the index of the item to remove and the number of elements to delete. Here's an illustration:
const array = [1, 2, 3, 4, 5];
const indexToRemove = 2; // Index of the item to remove
array.splice(indexToRemove, 1); // Remove one item at index 2
console.log(array); // [1, 2, 4, 5]
Using the filter() method:
The filter() method returns a new array containing all elements that pass a test given by a function. You can use it to make a new array that excludes the item you wish to get rid of:
const array = [1, 2, 3, 4, 5];
const itemToRemove = 3;
const newArray = array.filter(item => item !== itemToRemove);
console.log(newArray); // [1, 2, 4, 5]
To remove many things, use splice():
When using splice() to remove several items from an array, you can specify the starting index and the number of items to delete:
const array = [1, 2, 3, 4, 5];
const startIndex = 1;
const itemsToRemove = 3;
array.splice(startIndex, itemsToRemove); // Remove 3 items starting from index 1
console.log(array); // [1, 5]
Using pop() or shift() to remove items from the ends:
If you want to remove an item from the beginning or end of an array, use pop() to remove the last item and shift() to remove the first item:
const array = [1, 2, 3, 4, 5];
array.pop(); // Remove the last item (5)
console.log(array); // [1, 2, 3]
array.shift(); // Remove the first item (1)
console.log(array); // [2, 3]
Practice More on: https://interviewplus.ai/developers-and-programmers/javascript/questions
Comments
Post a Comment