0

In this problem, I have been asked to 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.

Here is the snippet:

function nextInLine(arr, item) {
  // Your code here

  return item;  // 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));

How to make this code work? Thanks in advance!

4
  • You can use the push() function to add to the end of an array, and shift() to remove and return the first element. Commented Mar 30, 2017 at 20:03
  • Can you show me the entire code? I have been trying to use the push() method for appending the last element and shift() method for removing the first element. But its showing my the function nextInLine() is not giving desired output in the way its expects to be! Commented Mar 30, 2017 at 20:06
  • I have seen! :) Ironically if the tried this similar code.. But its not working as expected! :( The followings are checking out correct: 1) nextInLine([2], 1) should return 2 2) nextInLine([5,6,7,8,9], 1) should return 5 3) After nextInLine(testArr, 10), testArr[4] should be 10 but not the following... 4) nextInLine([], 1) should return 1 Commented Mar 30, 2017 at 20:12
  • 2
    @SidratulMuntahaIbneRahman Put all those requirements in the question, not a comment. Commented Mar 30, 2017 at 20:21

1 Answer 1

1

Use .shift() to remove and return the first element of an array, and push() to add a new element to the end of the array. In order to make

nextInLine([], 1)

return 1 you need to do the push() before shift()

function nextInLine(arr, item) {
  arr.push(item);
  return arr.shift();
}

// 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));

console.log(nextInLine([], 1));

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.