JavaScript Delete from a Given Position of JS Array (original) (raw)
Last Updated : 18 Nov, 2024
These are the following ways to delete an item from the given array at given position:
1. Using the splice() Method(Most efficient for in-place modifications)
The splice() method is the most versatile way to remove elements from any position in an array. It allows you to specify the index where the removal should start and the number of elements to remove.
JavaScript `
const a = [1, 2, 3, 4, 5]; let idx = 2; a.splice(idx, 1); console.log(a);
`
2. Using slice() and concat() Methods(Less efficient in terms of memory and speed)
While slice() does not modify the original array, you can use it to create a new array that excludes the element at the specified position. By combining slice() with concat(), you can efficiently delete an element from a given position.
JavaScript `
const a = [1, 2, 3, 4, 5]; const res = a.slice(0, 2).concat(a.slice(3)); console.log(res);
`
3. Using the filter() Method(Efficient when removing by value, not position)
If you know the value of the element you wish to delete (rather than its index), the filter() method can help. It creates a new array with all elements that pass a test defined by the callback function.
JavaScript `
const a = [1, 2, 3, 4, 5]; let idx = 3; const res = a.filter(i => i !== idx); console.log(res);
`
4. Using Destructuring to Skip Elements(Less efficient and not ideal for positional deletions)
Although it's not a built-in method for deleting elements, you can use array destructuring to create a new array that excludes the element at the specified position. This method is a bit more declarative and might be useful in scenarios where you want to handle array manipulations in a concise manner.
JavaScript `
const a = [1, 2, 3, 4, 5]; const [first, second, , ...rest] = a; console.log([first, second, ...rest]);
`