Arrange the array so that the item is placed at the beginning while maintaining the original order

Currently facing a roadblock with this particular issue. I am attempting to create a function that accepts an index as input and rearranges the element at that index in an array to be placed at the beginning, while keeping the order of the other elements accurate.

const unorderedArr = [item1, item2, item3, item4]
const reorderArr = (i, arr) => { 
 ...
}

const reorderedArr = reorderArr(2, unorderedArr)
// [item3, item4, item1, item2]

Open to any hints!

Answer ā„–1

To achieve the desired result, you can implement a swapping technique with the preceding element until the index reaches zero.

const
    switchElements = (array, i) => {
        while (i) {
            [array[i], array[i - 1]] = [array[i - 1], array[i]];
            i--;
        }
        return array;
    };

console.log(...switchElements(['item1', 'item2', 'item3', 'item4'], 2));

Answer ā„–2

Here is a simple way to achieve this:

const unorderedArr = ["item1", "item2", "item3", "item4"];
const reorderArr = (i, arr) => {
  const movingElement = arr[i]; // get the element at index i
  arr.splice(i, 1); // remove the element from index i next to one ( item 3)
  arr.unshift(movingElement); // add the element to the beginning of the array
  return arr;
};

const reorderedArr = reorderArr(2, unorderedArr);
console.log("reorderedArr", reorderedArr);
//  [ 'item3', 'item1', 'item2', 'item4' ]

Answer ā„–3

slice(i) function will retrieve an array starting from the specified index (inclusive), while slice(0, i) will extract an array from the beginning to the index specified (excluding). The resulting array will be:

["item3","item4","item1","item2"]
const unorderedArr = ['item1', 'item2', 'item3', 'item4']
const reorderArr = (i, arr) => { 
  return [...arr.slice(i), ...arr.slice(0,i)];
}

const reorderedArr = reorderArr(2, unorderedArr);
console.log(reorderedArr)

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

Modify the width of the progress bar in Bootstrap using AngularJS

I'm new to AngularJS and I'm attempting to dynamically update the width of a progress bar based on changes in my controller. Here is what I currently have: <span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span> <div ...

What happens if I attempt to pass a blank field in multer?

I am trying to verify if the image field passed to Multer will include the file. There are no errors being thrown by Multer and the server is currently processing the request. ...

Retrieving data from a server using the GET method with parameters through axios in a React Native application

As someone new to Web requests, I have encountered a challenge that seems simple but has proven difficult for me. Despite searching the web, I am struggling to get a working response. When I input the URL 'http://www.test.com/callservice.php?action=s ...

Is it possible for two Bootstrap icon class names to be used sequentially with one taking precedence over the other?

I am having an issue with toggling a class name in my code. I have a class named (bi bi-clipboard) and I want to change it to (bi-clipboard-check) when it is clicked. However, the problem is that the new class name gets added next to the existing one like ...

Various JSON Tag values occurring more than once

Upon receiving a JSON Object in HTML, I am passing it to a JavaScript function defined below. The issue arises when the same folderName appears repeatedly on the HTML page. JSON Object: { "folderName": "arjunram-test", "objects": [ { ...

Using three.js to retrieve the camera's position using orbit controls

In my journey using three.js orbit controls, I have encountered a challenge of making a skybox follow the camera's position. Despite scouring the internet, I have not come across a suitable solution. My query is straightforward - how can I obtain the ...

"Encountering an unidentified custom element in Vue 2 while exploring Vue libraries

In my Vue project, I have integrated libraries like FusionCharts and VueProgressBar. However, I encountered an error in my console: Unknown custom element: <vue-progress-bar> - did you register the component correctly? For recursive components, make ...

$scope variables, ng-hide/show directive

There seems to be a confusion with $scope in my code. I have ng-hide/shows that use a variable in the top nav, controlled by "NavController". Inside an ng-view, controllers are linked via the app config function. The appointment setting functionality is ha ...

Styling Discord with NodeJS

After coding with Python for Discord, I decided to switch to JavaScript for its wider functionality. However, I encountered a formatting issue with a specific line of code while testing out a music bot in JS. The bot was sending an embed message, but I wan ...

Why is it that my React app is on a different port than the Express server that it listens to?

As I'm working on my React app, it currently runs on the default port http://localhost:3000/. However, when I need to communicate data from the client to the server, I have to listen on a different port. Take a look at the below code snippet: const ex ...

Using MongoDB Object as middleware in Express applications

Iā€™m facing issues trying to access the "DB" database object that gets created when the MongoDB client module establishes a connection with my MongoDB database. Currently, I am encountering an error indicating that in data.js, 'db' is not defin ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox <a href="https://codesandbox.io/p/github/cloudmako09/btu-calc/main?im ...

Setting up and Building Arrays of Objects in C++

When initializing an array of objects, do all the objects get constructed immediately or is construction required after initialization? To illustrate this scenario, consider the following: Suppose we have a class like this: class Object{ public: int ...

Swapping the icon in the panel heading of Bootstrap 3 Collapse based on its collapse status

Despite many attempts, I haven't been able to make any of the provided answers work in my code. My setup involves using Bootstrap 3 panels and collapse functionality to display advertisements. In the default view, only the advertisement heading is vi ...

Separating Angular controllers into their own files can help prevent errors like "undefined is not a

I am currently revamping some Angular code and my goal is to organize things by type, such as keeping controllers in a separate folder. Currently, I have two controllers and an app.js file. However, I am encountering an issue with the error message "undef ...

Best practices for sorting a value while iterating through a map in ReactJS

Currently working on learning React JS by replicating a PHP website I previously developed. I've successfully used Axios to fetch data from the database and display it on the frontend. Now, I'm facing a challenge where I need to sort the results ...

Unexpected outcomes when generating jQuery pages using CSS

I have created a piece of JavaScript code that populates 3 divs with icons in even rows. However, I am facing an issue where my first two rows align as expected, but the third row starts aligned with .col-5. Can you help me troubleshoot this? function row ...

Adjust the text within the paragraph dynamically according to the option chosen in the drop-down menu using

I'm having trouble updating a paragraph in a letter based on the user's selection from a dropdown menu. I can't seem to figure it out. I don't know whether ng-show/hide or ng-options is the best approach for this. I feel completely los ...

Nested within an it block are Protractor Jasmine describe blocks

Initially, the code provided below appears to be functioning properly. However, I have not come across anyone using this method before, leading me to question its validity and potential unforeseen drawbacks. The scenario involves writing an end-to-end tes ...

Arrange an array of objects by making a nested API call in Angular

My task involves sorting an array of objects based on the response from the first API call in ascending order. The initial API call returns a list of arrays which will be used for the subsequent API call. The first API call fetches something like this: [0 ...