Harish
Harish

Reputation: 636

How to delete an array element in JavaScript without using any of built-in Array methods?

I want to write my own implementation of array element deletion method. Why? - Because I am interested to know the algorithm behind the array element deletion and would like to take a stab at that.

I tried delete operator but it just sets the element to undefined. I don't want to use any of the existing built-in methods of Arrays such as splice, shift, pop, etc.

Is it even possible to achieve this? I am not looking for whole script but an idea and a direction on how to proceed would help. May be suggest me the topics I could explore to get an answer.

I have seen other posts related to array element deletion but they all use splice, pop, shift methods.

Upvotes: 0

Views: 2883

Answers (2)

mondersky
mondersky

Reputation: 471

 tab=[1,2,3,4,5]
    function new_splice(index,arr){
        for(i=0;i<arr.length-1;i++)
            if(i==index-1){
                for(j=i;j<arr.length-1;j++)
                    arr[j]=arr[j+1]
            }
            new_arr=[];
            for(i=0;i<arr.length-1;i++)
                new_arr[i]=arr[i]
        return new_arr;
    }
    document.write(new_splice(1,tab))

Upvotes: 0

SilentTremor
SilentTremor

Reputation: 4902

You can create your own deletion method:

Array.prototype.flush = function() {console.log(this.length = 0);}

Usage:

var test = [1, 2, 3];
alert(test);
test.flush();
alert(test);

UPDATE 1 Deletion method: if I understand correct: specify position, delete one element. If not better use is Array.prototype.splice(), anyhow, if you asked:

Code:

Array.prototype.delete = function(pos){ 
 if (pos < this.lenght) {
  this.splice(pos, 1);  
  return this
 } 
 throw "index " + pos + " outside of array length";
}

usage:

var test = [1, 2, 3];
    alert(test);
    test.delete (1);
    alert(test);

UPDATE 2 JavaScript Array delete without prototype methods usage:

Array.prototype.delete = function (pos) {
  if (!this.length) throw 'array is empty';
  if (pos < this.length) {
    for (var i = pos; i < this.length - 1; i++) {
      if (i < pos) continue;
      this[i] = this[i + 1];
    }
    this.length = this.length - 1;
    return this;
  }
  throw 'index ' + pos + ' outside of array length';
}
var foo = [1, 2, 3];
foo.delete(0);
alert(foo);
foo.delete(0);
alert(foo);
foo.delete(0);
alert(foo);
foo.delete(0);
alert(foo);

Upvotes: 1

Related Questions