Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 807
Weed Smith Avatar asked Apr 13 '26 20:04

Weed Smith


1 Answers

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);
like image 90
Nina Scholz Avatar answered Apr 16 '26 11:04

Nina Scholz