delete operator allows you to remove a key and its associated value from an array. However, it does not affect the length of the array. The key's place is still retained in the array, but it becomes
let array = ['one', 'two', 'three']; delete array; console.log(array); // Output: ['one', undefined, 'three']
splice() method can be used to add/remove items to/from an array and returns the removed item(s). This method changes the original array, meaning it actually removes the key and the length of the array is modified.
let array = ['one', 'two', 'three']; array.splice(1, 1); console.log(array); // Output: ['one', 'three']
In the above example,
splice() takes two parameters. The first is the index at which to start changing the array, and the second is the number of elements to remove.
filter() method creates a new array with all elements that pass the test provided by the given function. It's a non-destructive way of removing an item from an array based on a condition.
let array = ['one', 'two', 'three']; array = array.filter((item, index) => index !== 1); console.log(array); // Output: ['one', 'three']
In this example, the filter function is used to create a new array that includes all elements for which the provided filtering function returns
true. The function is a test that checks each index and only returns
true if the index is not equal to 1.
shift() methods can be used to remove keys from the end and the beginning of the array, respectively.
pop() removes the last element from an array and returns that element. This method changes the length of the array.
let array = ['one', 'two', 'three']; array.pop(); console.log(array); // Output: ['one', 'two']
shift() removes the first element from an array and returns that removed element. This method changes the length of the array.
let array = ['one', 'two', 'three']; array.shift(); console.log(array); // Output: ['two', 'three']
shift() modify the original array,
filter() offers a non-destructive alternative by creating a new array.
Choose the method that best suits your specific requirements, and ensure to understand its implications on your array's structure.
Did you find this article valuable?
Support 0xTristan by becoming a sponsor. Any amount is appreciated!