JavaScript Program to Delete Middle Element from an Array
Last Updated :
01 Aug, 2023
In this article, we will learn different approaches to how we can delete the middle element from a given array. We will use these JavaScript methods to achieve this:
Methods to Delete Middle Element from an Array
- Using JavaScript Spread Operator
- Using JavaScript splice() Method
- Using JavaScript delete Operator
- Using JavaScript array filter() Method
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected.
Syntax:
let variablename1 = [...value];
Example: In this example, we will use the JavaScript spread operator to create a new array without the middle element.
Javascript
let Arr = [1, 2, 3, 4, 5, 6];
let middleIndex = Math.floor(Arr.length / 2);
let newArray =
[...Arr.slice(0, middleIndex), ...Arr.slice(middleIndex + 1)]
console.log(newArray);
|
The JavaScript Array splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements.
Syntax:
Array.splice( index, remove_count, item_list )
Example: In this example, we will use the JavaScript splice method to delete the middle element.
Javascript
let Arr = [1, 2, 3, 4, 5, 6];
let middleIndex = Math.floor(Arr.length / 2);
Arr.splice(middleIndex, 1);
console.log(Arr);
|
The delete operator is used to delete JavaScript objects and object properties.
Syntax:
delete object;
delete object[property];
Example: In this example, we will use the JavaScript delete operator to delete the middle element.
Javascript
let Arr = [1, 2, 3, 4, 5, 6];
let index = Math.floor(Arr.length / 2);
delete Arr[index];
console.log(Arr);
|
Output
[ 1, 2, 3, <1 empty item>, 5, 6 ]
The JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
Syntax:
array.filter(callback(element, index, arr), thisValue)
Example: In this example, we will use the JavaScript array.filter() method to create a new array without the middle element.
Javascript
let Arr = [1, 2, 3, 4, 5, 6];
let middleIndex = Math.floor(Arr.length / 2);
let newArray =
Arr.filter((e, i) => i !== middleIndex)
console.log(newArray);
|
Share your thoughts in the comments
Please Login to comment...