New elements can be inserted at the rear of the queue while older elements are removed from the front of the queue

I'm new to JavaScript and currently working on a task involving queues. Here is the task description:

Create a function called nextInLine that takes an array (arr) and a number (item) as parameters. The function should add the number to the end of the array, then remove the first element of the array. Finally, the nextInLine function should return the element that was removed.

function nextInLine(arr, item) {
  // Write your code here
  
  return item; // Modify this line
}

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

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Adjust this line for testing
console.log("After: " + JSON.stringify(testArr));

Expected results:

  • nextInLine([], 1) should return 1
  • nextInLine([2], 1) should return 2
  • nextInLine([5,6,7,8,9], 1) should return 5
  • After nextInLine(testArr, 10), testArr[4] should be 10

Answer №1

Give this a shot:

function dequeue(array, element) {
  // Add your code here
  array.push(element);
  var output = array[0];
  array.shift();
  return output;  // Don't forget to update this line
}

// Setting up the test
var originalArray = [5, 10, 15, 20, 25];

// Showcasing the code
console.log("Before: " + JSON.stringify(originalArray));
console.log(dequeue(originalArray, 50)); // Update this line for testing
console.log("After: " + JSON.stringify(originalArray));
console.log(dequeue(originalArray, 20));

Answer №2

VIEW DEMO

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

console.log(retrieveFirst([], 3)); // 3
console.log(retrieveFirst([6], 9)); // 6
console.log(retrieveFirst([2,4,6,8,10], 12)); // 2

Answer №3

function moveToFrontOfLine(array, newItem) {
// Your implementation goes here
array.push(newItem);
return array.shift(); // Update this line according to your logic
}
// Setting up the test scenario
var testArray = [1, 2, 3, 4, 5];
// Showing the result
console.log("Initial Array: " + JSON.stringify(testArray));
console.log(moveToFrontOfLine(testArray, 10)); // Adjust this line for testing
console.log("Final Array: " + JSON.stringify(testArray));
console.log(moveToFrontOfLine(testArray, 4));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the forEach method, we can create multiple buttons in ReactJS and also access the onClick handler

I have a button with both the label and onClick properties. Additionally, I have an array containing the values I need to assign to the label property. Here is the code snippet: render(){ {tabel_soal.forEach(function (item, index) { <Ra ...

Is there a way to incorporate various string values in a single function?

I am relatively new to programming and currently working on a project to display GPS locations from Lightroom on a Google Maps interface. After printing the strings to the screen, I can see 5 different values as expected. However, I am struggling to use t ...

Establish a connection between servers operating on two distinct ports

I'm completely new to JavaScript and developing web applications. I have set up two servers on my computer running on separate ports (5000 and 5001). The server on port 5000 needs to communicate with the one on port 5001, but I'm struggling to g ...

React Router 4 - Optimizing Component Refresh by Remounting Instead of Re-Rendering

I am currently in the process of configuring a React project that utilizes React Router 4 ("react-router-dom": "^4.3.1"). Within this project, I have implemented a SideBar, a NavBar, and the main content section of the application which changes based on th ...

Converting a string to a date type within a dynamically generated mat-table

I am working on a mat-table that shows columns for Date, Before Time Period, and After Time Period. Here is the HTML code for it: <ng-container matColumnDef="{{ column }}" *ngFor="let column of columnsToDisplay" > ...

Uh-oh! It seems like there is a deployment error in NextJS on Vercel. The issue is that Nested

Suddenly, my middleware ceased to function properly during deployment. The error message states: > Build error occurred NestedMiddlewareError: Nested Middleware is not allowed, found: pages/_middleware Please relocate your code to a single file at /midd ...

Leveraging AJAX for transmitting form information to a php script without relying on jQuery

I want to explore AJAX by implementing a basic form data submission to a php script and database. For educational purposes, I've reached a standstill after hitting the "Create Profile" button with no action. Could someone spot any syntax or structural ...

What issue lies within this particular for loop?

Hey everyone, I'm having trouble with my code that involves appending an array to the DOM. Here's what I have: function inputFeedContent(data){ for(var k=0; k < columns; k++) { var col = "<div class='col-1'>"; ...

Jquery Validation Plugin - Specifically for validating numeric inputs in specific situations

I am currently working on implementing validation using jQuery Validate for a numeric value, but only when a specific radio button is checked. If the radio button is not checked, the field should be required and allow alphanumeric values to be entered. How ...

Learn the process of utilizing JavaScript/Node.js to dynamically upload images onto a webpage directly from a database

Currently, I am developing a web application and building a user profile page where I aim to showcase user information along with a profile picture. Working with node/express/jade stack, I have a javascript file that manages loading the appropriate jade vi ...

What is the most effective method for testing event emitters?

Imagine I have a basic component structured like this: @Component({ selector: 'my-test', template: '<div></div>' }) export class test { @Output selected: EventEmitter<string> = new EventEmitter<string>() ...

What is the best way to retrieve the nearest or preceding object regardless of the document's layout using jQuery?

Here are some examples to illustrate the concept: <ul> <li id="o1" class="elem">apple</li> <li id="o2" class="elem">banana</li> <li id="o3" class="elem">orange</li> </ul> **$('#o2').exact ...

What is the process for adding elements to an object in Angular JS?

My goal is to send data to an ng-object after filling out and submitting an HTML form with user-defined values. However, after pressing submit, the values are being duplicated. I have attempted to clear the data by using $scope.user > $scope.user=&apos ...

Pass a PHP array to JavaScript and use jqplot to create a plot

I am currently using jqplot to plot data that originates from a PHP array. However, I have encountered an issue when trying to plot the data using JavaScript. Here is the PHP code: $array= array(); $array[] = 34.890; $array[] = 25.090; And here is the c ...

Utilizing jQuery UI Slider for Calculating Percentage

I recently worked on an example where I incorporated 5 sliders, which you can see here: Example: http://jsfiddle.net/redsunsoft/caPAb/2/ My Example: http://jsfiddle.net/9azJG/ var sliders = $("#sliders .slider"); var availableTotal = 100; ...

retrieving information from a data attribute

When setting a data attribute for a user on a link, the code looks like this: <input type="button" class="btn" data-user={"user": "<%= @user.name %>"} value="Start" id="game"> Upon listening for the click event in the JavaScript function, co ...

AJAX brings back the previous value from an array

I am currently working on a website that will showcase various artwork. The concept involves using JavaScript to run a php file when the page loads, which in turn queries the server for the names and IDs of the image files (artwork.jpg) and displays them a ...

Why does the data continue to remain empty?

I am currently working with a JSON object: {"suggestions":["M.I.A.","M.","Mindless Self Indulgence","The Cure","Telefon Tel Aviv","M","J. Ralph","Jason Mraz","Carbon Based Lifeforms","Cycle of Pain","Chantal Kreviazuk","-M-","ayumi hamasaki","R.E.M.","Don ...

Is there a method to iterate through dynamically added nested arrays, similar to the Russian Matryoshka dolls?

I am facing a challenge in my Angular TypeScript class where I need to define a function that can loop through dynamically added nested arrays. The issue arises because my template displays a custom Kendo grid which requires me to traverse a type of "Matri ...

To obtain the desired response, I must make an additional GET request

Upon sending the first GET request to this endpoint, I receive a response of allEvents = []. However, if I wait a few seconds and hit the endpoint again, I get the desired results with a populated allEvents array. It seems that the function is not executin ...