Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIFO behavior for Array.pop in javascript? [duplicate]

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
like image 765
cinead Avatar asked Jan 05 '16 22:01

cinead


People also ask

What does the pop () method in an array do in JavaScript?

pop() The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

What is FIFO in JavaScript?

A Queue works on the FIFO(First in First Out) principle. Hence, it performs two basic operations that is addition of elements at the end of the queue and removal of elements from the front of the queue.

What is the difference between pop () method and shift () method?

Shift() method removes the first element and whereas the pop() method removes the last element from an array. The Shift() returns the removed first element of the array. If the array is empty then this function returns undefined whereas the pop() method turns the removed element array.

Does array use FIFO?

Updated: Well arrays are neither LIFO or FIFO .


1 Answers

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

like image 149
Deblaton Jean-Philippe Avatar answered Sep 18 '22 19:09

Deblaton Jean-Philippe