js array to delete an item

Mondo Technology Updated on 2024-01-31

Suppose you have an array like this:

let arr=[1,2,3,4,5];

There are several ways to delete an array in j**ascript.

The splice() method accepts three parameters:

Start modifying the index position of the array (required).

The number of elements to delete (required).

A new element to add to the array (optional).

Note: The splice() method directly modifies the original array and returns the deleted element.

So if we want to remove the third element (arr[2], i.e. 3), we can do this:

let arr=[1,2,3,4,5];

arr.splice(3, 1);Delete the element of index 2 and delete 1 element.

console.log(arr);Output: [1,2,4,5].

The filter() method takes as an argument a function that will be called by each element in the array. If the function returns true for an element, then that element is included in the new array;If false is returned, it will not be included. This method does not change the original array, but returns a new one.

So if we want to remove the third element (arr[2], i.e. 3), we can do this:

let arr=[1,2,3,4,5];

let newarr=arr.filter((item,index)=>index!==2);The element of index 2 is culled and a new array is returned.

console.log(newarr);Output: [1,2,4,5].

If what we want to remove is the last element (arr[4], i.e. 5), we can use the pop() method:

let arr=[1,2,3,4,5];

arr.pop();Deletes and returns the last element of the array.

console.log(arr);Output: [1,2,3,4].

If what we want to remove is the first element (arr[0] i.e. 1), we can use the shift() method:

let arr=[1,2,3,4,5];

arr.shift();Deletes and returns the last element of the array.

console.log(arr);Output: [2,3,4,5].

The slice() method can extract a portion of the array and return a new array object. This method does not change the original array. Accept two parameters:

start (required): The index at the beginning of the extraction (inclusive). If the index is negative, then the extraction will start counting from the end of the array. For example, -1 for the last element, -2 for the penultimate element, and so on.

end (optional): The index at the end of the extraction (not included). If the parameter is omitted or the index is larger than the array length, the extraction will go all the way to the end of the array. If the index is negative, then the extraction will start counting from the end of the array.

So if we want to remove the first element (arr[0], i.e. 1), we can do this:

let arr=[1,2,3,4,5];

let newarr=arr.slice(1);Start extracting from the second element, returning a new array.

console.log(newarr);Output: [2,3,4,5].

If what we want to remove is the last element (arr[4] i.e. 5), we can do this:

let arr=[1,2,3,4,5];

let newarr=arr.slice(-1);Start extracting from the penultimate element, returning a new array.

console.log(newarr);Output: [1,2,3,4].

Related Pages