- Learning JavaScript Data Structures and Algorithms
- Loiane Groner
- 342字
- 2021-08-27 18:41:15
Removing an element from the first position
To remove a value from the beginning of the array, we can use the following code:
for (let i = 0; i < numbers.length; i++) { numbers[i] = numbers[i + 1]; }
We can represent the previous code using the following diagram:

We shifted all the elements one position to the left. However, the length of the array is still the same (17), meaning we still have an extra element in our array (with an undefined value). The last time the code inside the loop was executed, i+1 was a reference to a position that does not exist. In some languages, such as Java, C/C++, or C#, the code would throw an exception, and we would have to end our loop at numbers.length -1.
We have only overwritten the array's original values, and we did not really remove the value (as the length of the array is still the same and we have this extra undefined element).
To remove the value from the array, we can also create a removeFirstPosition method with the logic described in this topic. However, to really remove the element from the array, we need to create a new array and copy all values other than undefined values from the original array to the new one and assign the new array to our array. To do so, we can also create a reIndex method as follows:
Array.prototype.reIndex = function(myArray) { const newArray = []; for(let i = 0; i < myArray.length; i++ ) { if (myArray[i] !== undefined) { // console.log(myArray[i]); newArray.push(myArray[i]); } } return newArray; } // remove first position manually and reIndex Array.prototype.removeFirstPosition = function() { for (let i = 0; i < this.length; i++) { this[i] = this[i + 1]; } return this.reIndex(this); }; numbers = numbers.removeFirstPosition();