Need some help in queue (Task 175)

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

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.

I’ve no idea how to do this. Would someone explain this to me.
Thanks

To add something to the end of the array, you can use push() :

var array = [0,1,2,3];
array.push(4);
console.log(array); // [0,1,2,3,4];

to remove the first element of an array, you can use shift() :

var array = [0,1,2,3];
var removedElement = array.shift();
console.log(array); // [1,2,3]
console.log(removedElement); // 0
// note that shift() removes an element of an array and returns the removed element as well
3 Likes

Thanks for replying. But It didn’t helped me to solve the task :slight_smile: wheres argument

as Omegga said, using push and shift methods will do the trick.

so nextInLine(testArr, 6) will remove the first element 1 from the array and will add 6 to the end of it so testArr will be [2,3,4,5,6] and the return value of the function should be 1.

1 Like

I agree that the problem isn’t explained very well. I just tried to use the push and shift commands but it still isn’t solving the problem for me.

function nextInLine(arr, item) {
// Your code here
arr.push(1);
arr.shift(6);
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));

I do get a changed result:

function nextInLine(arr, item) {
// Your code here
arr.push(1);
arr.shift(6);
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));

but when I modify the next in line console log, I don’t get the desired results. Can someone please explain what Im doing wrong?

I’m not clear with the answer. But this will complete the task

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

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

1 Like

Thanks so much @Charuka. i still need to study it but that got me past the problem