Weed Smith
Weed Smith

Reputation: 33

Removing the first element in an array without using array methods

So I have homework that requires me to dequeue from an array like so:

let arr = [1, 2, 3]

My only problem is that I'm restricted in using any array method except for the .length method.

I have tried using the delete to remove the first element but I know it doesn't adjust the array and reflects undefined for the first element:

function dequeue(){
  delete arr[0];
  console.log(arr)
}

Any help or advice on how to do it is highly appreciated.

Upvotes: 3

Views: 1439

Answers (4)

Akash Singh
Akash Singh

Reputation: 31

For left shift:

function shiftArrLeft(arr) {
        let a = arr[0];
        let newArr = [];
        for (let i = 1; i <= arr.length - 1; i++) {
            newArr[i - 1] = arr[i];
        }
        newArr[newArr.length] = a;
        console.log(newArr);
    }

For right shift:

function shiftArrRight(arr) {
    let a = arr[arr.length - 1];
    let newArr = [];
    for (let i = 0; i < arr.length - 1; i++) {
        newArr[i + 1] = arr[i];
    }
    newArr[0] = a;
    console.log(newArr);
}

Upvotes: -1

LHDi
LHDi

Reputation: 434

You can use Destructuring assignment. try this out:

const [firstElement, ...restOfTheArray] = yourArray;

restOfTheArray is the same array with the first element removed.

Upvotes: 0

Godnyl Pula
Godnyl Pula

Reputation: 125

If .map is allowed to use in your case.

array = array.map((elm,index,arr) => arr[index+1]);
array.length--;

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386720

Assuming, you can still use assigment with index, you could copy all items one index before and decrement the length of the array.

let array = [1, 2, 3];

for (let i = 1; i < array.length; i++) array[i - 1] = array[i];

array.length--;

console.log(array);

Upvotes: 4

Related Questions