-3

I'm trying to remove an element from an array using this instructions:

  1. Use a loop to shift array values as follows. Starting with the index argument; for indexes less than length - moving one index towards the end set the array value at the current index to the array value at the following index

           Example: remove value at index 2 in List: a  b  c  d  e
    
                               0  1  2  3  4
                 before loop:  a  b  c  d  e
           after loop pass 1:  a  b  d  d  e  (index 2 copies 'd' from index 3)
           after loop pass 2:  a  b  d  e  e  (index 3 copies 'e' from index 4)
           (loop ends)
    
  2. Decrease array length by one; in JavaScript, this drops the last element from the array.

Why my code is not working?

 this._data = ["a", "b", "c", "d", "e"];


length() {
        return this._data.length;
    }
    
remove(index) {

            if (index === this.length()) {
                delete this._data[this.length()];
            }
            
            
            while (index < this.length()) {
                this._data[index] = this._data[index + 1];
                index++;
            }
            delete this._data[this.length() - 1];
            
    }
Ricard
  • 1
  • 2

1 Answers1

0

Your code is awful, you couldn't use the property .length on something that doesn't have the attribute, you should initialize the object and call it after (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)

var arr = ["a", "b", "c", "d", "e"];
arr.splice(2, 1); /* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice */
/* ["a", "b", "d", "e"] */

or

var arr = ["a", "b", "c", "d", "e"];        
function remove(arr, index){
    if(Array.isArray(arr) && Number.isInteger(index) && index >= 0 && index < arr.length){
        for(var i = index; i < arr.length - 1; i++){
            arr[i] = arr[i + 1];
        }
        arr.pop(); /* https://stackoverflow.com/questions/19544452/remove-last-item-from-array */
    }
}   
remove(arr, 2);
romph
  • 487
  • 3
  • 11