19

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
2
  • 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" Commented Jan 5, 2016 at 22:31
  • Aa shift() is expensive on large arrays, you may want to use the tiny tiny-queue library instead. Commented Oct 19, 2018 at 22:02

2 Answers 2

52

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

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.