13aal 13aal - 1 year ago 74
Javascript Question

Writing a functions that removes an array and adds to the list

I'm currently learning Javascript at freecodecamp and am at the point where I'm learning about functions.

I'm on a task that is asking me to right a type of

that will removed the first item from the array, and replace it with another (at the end of the array).

Here's what I have so far:

function nextInLine(arr, item) {
// Your code here
array = [];
return arr; // Change this line

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

However when run with the test setup it out puts:

Before: [1, 2, 3, 4, 5]

After: [1, 2, 3, 4, 5]

I'm confused as all get out.. How would I accomplish this task?

Actual task:

In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.

Write a function nextInLine which takes an array (arr) and a number (item) as arguments. Add the number to the end of the array, then remove the first element of array. The nextInLine function should then return the element that was removed.

Answer Source

tl;dr You're using Array.prototype.shift and Array.prototype.push wrong.

shift removes the first item from an array and returns that item. Instead of

array = [];

You want to do

var firstItem = arr.shift();

push adds an item to the end of an array. You want to mutate the original array object in place, so you want to do


Then return the first item

return firstItem;

This gives you the following function:

function nextInLine(arr, item) {
  var firstItem = arr.shift(arr);
  return firstItem;