Reorder elements within an array while making sure to account for any blank spaces

I am currently developing a tool for staff/shift assignments, where each week the staff will be assigned tasks. For the following week, I want to shift all the staff down by one task on the list, with the last staff member cycling back to the top of the list.

The main challenge I'm facing is ensuring that any blank cells in the array remain in their positions while the staff members cycle around them.

Here is an example of what I am trying to achieve:

https://i.sstatic.net/W6hIJ.png

Although I have managed to make it work, I believe my code could be improved in terms of readability and maintainability. So, I am seeking better options.

Below is a functioning example:

let assignedStaff = [
  {periodId: 1, staffName: "Jimbo"},
  {periodId: 1, staffName: ""},
  {periodId: 1, staffName: "Lucy"},
  {periodId: 1, staffName: ""},
  {periodId: 1, staffName: "Claire"}];

let newPeriod = [];

//Get only the populated staff
populated = assignedStaff.filter(element => element.staffName !== "");

//Move the last staff member to the front
populated.unshift(populated.pop());

for(let i = 0, assigned = 0; i < assignedStaff.length; i++){
  
  if(assignedStaff[i].staffName !== ""){
    
    newPeriod.push(populated[assigned]);
    assigned++
    
  }
  else
    {
      newPeriod.push(assignedStaff[i])
    }
  
}

console.log(newPeriod);

For a more readable output, you can view the results on JSBin. It provides better clarity than the run snippet tool.

Answer №1

An alternative approach to achieve a cleaner solution involves initially removing the empty elements while retaining their indexes. Subsequently, execute a right rotation (

populated.unshift(populated.pop());
) and re-insert the empty elements at their original positions:

let assignedStaff = [
  {periodId: 1, staffName: "Jimbo"},
  {periodId: 1, staffName: ""},
  {periodId: 1, staffName: "Lucy"},
  {periodId: 1, staffName: ""},
  {periodId: 1, staffName: "Claire"}];

// [1, 3]
let emptyIndexes = assignedStaff.map((x, i) => x.staffName === "" ? i : null).filter(i => i !== null)
let cleanedStaff = assignedStaff.filter(x => x.staffName !== "")
cleanedStaff.unshift(cleanedStaff.pop())

for (const i of emptyIndexes)
    cleanedStaff.splice(i, 0, assignedStaff[i])
  
console.log(cleanedStaff)

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

What's causing the malfunction in this JavaScript function for capitalizing the first letter?

My React component includes a select box where users can choose one of four "severity" labels, all of which must be in lowercase due to API requirements. Here is the select box... <select id="logs-select" onChange={this.handleSeverityChange} value={thi ...

Is it possible to generate a unique name from an array without any repeats?

Update: I am not looking to create a single list, but rather a button that generates a random name when clicked. Objective: Generate a random name from an array by clicking a button. The goal is to display one name at a time randomly without repetition. W ...

Exploring each item within oData: A guide

After writing the code statement above, I am able to see the attached image. Now, my challenge is accessing the "label" property inside each object. How can I iterate through these objects and retrieve their "label" properties? item.getModel().oData; I a ...

Utilizing NextJS to Call the Layout Component Function from the Page Component

I can't seem to find an answer to this question for Next.js after searching online. While there are solutions available for React, I don't think they will work in the Next.js framework. My application is essentially a shop with a navigation menu ...

Implementing onbeforeunload event on body tag with jQuery for Chrome and IE browsers

My current system includes a feature where I need to confirm with the user if they really want to leave the page once a dirty flag is set. I have implemented the following code - when viewing in Firefox, I can see that the page source shows the onbeforeun ...

Alternative to Lodash for performing a check operation in JavaScript and assigning a new value

Recently, I've been utilizing a code snippet to verify the value of an input field located at index:1 within an array. The code looks like this: const inputValue=journeyData && journeyData.birthdate && journeyData.birthdate[0] ...

Laravel: JavaScript Integration Problem (Current Status Concern)

I encountered an issue with the update status feature. The status is being stored correctly in the database, but the corresponding status icon does not change as expected. Upon refreshing the page, the status icon reverts to its previous position, even tho ...

Implementing an onclick event listener in combination with an AJAX API call

I'm really struggling with this issue. Here's the problem I'm facing: I have a text area, and I need to be able to click on a button to perform two tasks: Convert the address text into uppercase Loop through the data retrieved from an API ...

When passing parameters as an array in PHP, remember to use "[ ]"

My function receives parameters as an array: public myFunction($options = array("option1"=>true, "option2"=>true, "option4"=>"astring"), $anotherparameter = 0) { if($options["option1"] === true) { //Perform all the necessary operatio ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

The task in gulp-run-sequence remains incomplete

The gulp-tasks I have set up are designed to revision static files and update the links to them. var config = require('./config'); var gulp = require('gulp'); var rev = require(& ...

Build a custom loader in Next JS that leverages Webpack to dynamically map URL paths to specific components

I am looking to implement a custom loader in Next.js that leverages Webpack through the next.config.js configuration file. This loader should route Blog.js for the /blog route and Tutorial.js for the /tutorial route. The MDX data is stored in the pages/ d ...

What is the best way to remove characters from a string that fall outside the a-z and 0-9 range?

I am aware of a similar version but I am seeking the easiest method? $string = "HeLLo$ my222 name is zolee0802343134"; $string = strtolower($string); $replacement = range (a, z); $replacement2 = range (0, 9); // What code should be inserted here? // ...

Determine which file to load based on the size of the browser

I have a quick question regarding the correct syntax. I am trying to only load the jQuery file if the browser screen width is less than 1100px. <script type="text/javascript"> $(document).ready(function() { if ($(window).width() < 1100) { ...

"Troubleshooting the event.target[matches] issue encountered during form submission in a Meteor React project

Can anyone help me with this bug I'm facing? Here is the issue: To summarize, I have a form for creating events and I want the handleSubmit() function to manage error messages and add the event to the database if there are no errors. I previously had ...

JavaScript: The power of nested array manipulation

I'm having trouble extracting data from a parsed JSON array obtained from a shipping company. Specifically, I am attempting to retrieve the short_name of Cleveland, OH, but all my attempts to access this information have been unsuccessful. When I use: ...

A more concise validation function for mandatory fields

When working on an HTML application with TypeScript, I encountered a situation where I needed to build an error message for a form that had several required fields. In my TypeScript file, I created a function called hasErrors() which checks each field and ...

Matching a regular expression pattern at the beginning of a line for grouping strings

One of my tasks involves working with a markdown string that looks like this: var str = " # Title here Some body of text ## A subtitle ##There may be no space after the title hashtags Another body of text with a Twitter #hashtag in it"; My goal ...

Animating a CSS shape with the .animate method

I need help creating a dynamic graphic for my school project using css, jquery, and html. I want to make a rectangle that moves across the screen, but I'm having trouble getting it to work properly. Despite trying different variations of the animate f ...

JavaScript: Identify the variable that has been updated

When checking for changes in the values of a couple of variables, I use the following condition: <% if (ctx.recipient.@firstName != ctx.recipient.@firstName_init || ctx.recipient.@lastName != ctx.recipient.@lastName_init || ctx.recipient.@emailPreferred ...