Tag Archives: left shift of array elements after removal an item

JavaScript / Any language: Delete a specific array element and shift other elements after deletion

How to delete a specific array element and shift other elements after deletion in JavaScript or any other programming languages

Here I have used an array , to be precise, predefined fixed array I have used here.
Initial array is [15,10,20,22,1,3,6].

Then I have decided to delete an item based on a comparison, here I have chosen to delete item 20.
After deletion the array will be : [15,10,22,1,3,6]

Initially after assigning the array by the statement var myArray = [15,10,20,22,1,3,6];
myArray[6]=6 and
array length = 7 found by the statement myArray.length;

After deletion the the item 20 will be deleted i.e myArray[2] and (after delete) myArray[2] will hold (before delete) myArray[3] i.e 22, (after delete) myArray[3] will hold (before delete) myArray[4] value i.e 1.

So , after deletion the array elements will be as follows :
array length = 6

Below we have used JavaScript splice() method, but this shifting and delete can be done without this method. I am giving you a hint.

I have not used this splice() method in the following JavaScript code snippet, you can use it also instead of the code in Gray.

Make deletion and shifting without splice() method in JavaScript. The following algorithm will work in any programming language.

The algorithm :
Step1: first reach the item which you want to delete by a FOR LOOP,
Step 2: Then get the ARRAY INDEX of that element.
Step 3: Then assign next array element to that element. Assign next array element to that element to shift and continue the process.

// Make shifting a global variable.
var shifting = 0;
for(var i = 0; i <= myArray.length-1; i++) { if(myArray[i] == 20) shifting = 1; if(shifting == 1) myArray[i] = myArray[i+1]; }

Delete an array element and shift the rest of the element by the help of SPLICE() method in JavaScript.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var myArray = [15,10,20,22,1,3,6];
document.write("<br />"+myArray);
document.write("<br />Before delete Array Length : "+myArray.length);
for(var i = myArray.length-1; i >= 0; i–)
if(myArray[i] == 20)
document.write("<br />After deleting item 20 the array becomes : "+myArray);
document.write("<br />Array Length : "+myArray.length);