In JavaScript, there are several ways to exclude particular entries from an array. You can choose a method based on whether you’ll identify the item by its value or its index if the pop() or shift() methods aren’t suitable for your needs.
Removing the Last Element of an Array
The pop() method removes and returns the last element of an array.
const myArray = [1, 2, 3, 4, 5];
const x = myArray.pop();
console.log(`The values of myArray are: ${myArray}`);
console.log(`The element x value is: ${x}`);
Output:
The values of myArray are: 1,2,3,4
The element x value is: 5
Removing the First Element of an Array
The shift() method removes and returns the first element of an array.
const myArray = [1, 2, 3, 4, 5];
const x = myArray.shift();
console.log(`The values of myArray are: ${myArray}`);
console.log(`The element x value is: ${x}`);
Output:
The values of myArray are: 2,3,4,5
The element x value is: 1
Removing an Element by Index
If you are identifying the item to be removed by its index, you can use the delete operator. If you want to use the value of the item you are removing, use the splice() method.
The delete Operator
The value at that position of the array will be undefined since the delete operator removes the object property at the designated index without changing the array’s length.
const myArray = [1, 2, 3, 4, 5];
delete myArray[1];
console.log(`The values of myArray are: ${myArray}`);
Output:
The values of myArray are: 1,,3,4,5
The splice() Method
The index of the element you want to remove and the index you want to remove up to are the two arguments that the splice() function requires. All of the values that were deleted from the original array are stored in a new array created by the splice() method. The length of the original array will be adjusted, and the values that were eliminated will no longer be present.
const myArray = [1, 2, 3, 4, 5];
const x = myArray.splice(1, 1);
console.log(`The values of myArray are: ${myArray}`);
console.log(`The element x value is: ${x}`);
Output:
The values of myArray are: 1,3,4,5
variable x value: 2
Removing an Element by Value
Once the index has been identified using the indexOf() method, you can delete the element from its index if you are identifying the element to be removed by its value. Use the filter() technique or a combination of the indexOf() and splice() methods if you wish to use the value of the element you are deleting.
Combining indexOf() and splice() Methods
The indexOf() method returns the index of the element in the array that corresponds to the value you pass in for the element you want to delete from your array. The element at the returned index is then removed using the splice() technique.
const myArray = [1, 2, 3, 4, 5];
const index = myArray.indexOf(2);
const x = myArray.splice(index, 1);
console.log(`The values of myArray are: ${myArray}`);
console.log(`The element x value is: ${x}`);
Output:
The values of myArray are: 1,3,4,5
The element x value is: 2

