Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

dynamic array in javascript

class DynamicArray{
    constructor(){
        this.length=0;
        this.data={}
    }

    get(index){
        return this.data[index];
    }

    push(element){
        this.data[this.length]= element;
        this.length++;

        return this.length;
    }

    pop(){
        if(this.length == 0)
            return undefined;
        
        const popElement = this.data[this.length-1];
        delete this.data[this.length-1];
        this.length--;

        return popElement;
    }

    insert(element, index){
        if(index> this.length-1 || index<0)
            return undefined;
        
        this.length++;
        for(let i= this.length-1; i>index; i--){
            this.data[i] = this.data[i-1];
        }
        this.data[index] = element;
        return this.data;
    }

    remove(index){
        if(this.length == 0)
            return undefined;
        
        if(index > this.length-1 || index < 0)
            return undefined;
        
        const removedItem = this.data[index];
        for(let i=index; i < this.length; i++){
            this.data[i]=this.data[i+1];
        }
        delete this.data[this.length-1];
        this.length--;

        return removedItem;
    }
}



const array = new DynamicArray();
array.push('Aayush');
array.push('Parth');
array.push('Abhishek');
array.push('Thalesh');
array.push('chiku');

console.log(array);
array.insert('Zoya',2);
console.log(array);
Source by learnersbucket.com #
 
PREVIOUS NEXT
Tagged: #dynamic #array #javascript
ADD COMMENT
Topic
Name
4+9 =