18

I want an Array method similar to Array.pop() that exhibits First In First Out behavior, instead of the native FILO behavior. Is there an easy way to do so?

Imagine a javascript console:

>> array = [];
>> array.push(1);
>> array.push(2);
>> array.push(3);
>> array.fifopop();
1      <-- array.pop() yields 3, instead
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
cinead
  • 317
  • 1
  • 2
  • 8
  • 6
    use `array.shift()` .... or use `array.unshift()` instead of `array.push()` then keep using `array.pop()` ... shift/unshift works on array "top" ... push/pop works on array "bottom" – Jaromanda X Jan 05 '16 at 22:31
  • Aa shift() is expensive on large arrays, you may want to use the tiny [tiny-queue](https://www.npmjs.com/package/tiny-queue) library instead. – MortezaE Oct 19 '18 at 22:02

2 Answers2

48

You can use array.prototype.shift()

>> array = [];
>> array.push(1);
>> array.push(2);
>> array.push(3);
>> array.shift();  //outputs 1 and removes it from the array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

Community
  • 1
  • 1
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
7

The method is array.shift(). It pulls the first array element much as array.pop() pulls the last element.

TheHans255
  • 2,059
  • 1
  • 19
  • 36