JavaScript function to sort an array by indexes specified in a second array

Consider this scenario: I require the capability to rearrange any one-dimensional array so that the new array begins with the center number (if the object count is odd) or the center two numbers (if the object count is even), and then progresses from low to high until all numbers in the original array are accounted for.

For instance, in the case of an odd number of objects:

Original Array: [1,2,3,5,8,13,20]

New Array: [5,3,8,2,13,1,20]

Or for an even number of objects:

Original Array: [1,2,3,4]

New Array: [2,3,1,4]

I attempted to achieve this using a for loop, which worked theoretically but could not be implemented as a computed property in Vue.js.


This was my unsuccessful attempt:

gameInfo: {
      cards: [1, 2, 3, 6, 8, 13, 21, 40, 1000],
    }

reorderOddCards() {
  ATTEMPT 1
  const cardCount = this.gameInfo.cards.length;
  const middleNumber = (cardCount / 2).toFixed(0);
  const newCardOrder = this.gameInfo.cards.map(addToArray);

  function addToArray(value, index) {
    if (index < middleNumber) {
      const newIndex = (((middleNumber - index) * 2) - 1);
      newCardOrder.splice(newIndex, 1, value);
    } else if (index === middleNumber) {
      newCardOrder.splice(index, 1, value);
    } else {
      const newIndex = ((middleNumber - index) * 2);
      newCardOrder.splice(newIndex, 1, value);
    }
  }

  return newCardOrder;
},

Another method involving a .sort function was considered, but implementation has proven challenging.

Potential Solution

Answer №1

To achieve this outcome, a straightforward while loop can be utilized. The pivotal aspect revolves around identifying the middle index(es). In an array with an odd length, there exists only one midpoint, which could be visualized as having the left and right midpoints aligning on the same spot to streamline the method. The resulting index is derived by dividing the length by two and taking the floor value. The right index will consistently match this value. However, in arrays of even lengths, the left index needs to decrease by one. Following the computation of these indices, we iterate through while decreasing the left index and increasing the right index to populate our resultant array.

function order(arr){
  let right = Math.floor(arr.length / 2);
  let left = right - (arr.length % 2 == 1 ? 0: 1);
  let res = left === right ? [arr[left]] : arr.slice(left, right + 1);
  while(left > 0){
    res.push(arr[--left]);
    res.push(arr[++right]);
  }
  return res;
}
console.log(...order([1,2,3,5,8,13,20]));
console.log(...order([1,2,3,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

Guide to resolving domain names in express.js

I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route. When I try to access the index page, everything seems to be working fine. Howev ...

Unable to load AngularJS thumbnails from JSON file? Learn how to showcase a larger image by clicking on the thumbnail

Working with AngularJS to retrieve image data from a JSON file has been successful for me. My next task involves loading all of the thumbnail images into the gallery div and populating the src, alt, and title attributes using ng-repeat. However, this part ...

Transferring data from ExpressJs to React application

Using multer, I am able to handle multipart form datas and store them in both the server and MongoDB. When registering a user, I save the image as a string in MongoDB, even though the actual image is located in /public/img/. const body = req.body; con ...

Tips for updating documents in MongoDB using NodeJS

I'm trying to update the document using the command below. order = await db.collection("orders").findOneAndUpdate({ order_id: req.body.ORDERID }, {$set: { payment_status: "Paid", paymentInfo: JSON.stringify(myrequest) }}) console. ...

"Use jQuery to toggle the slide effect for the first element of a

Below is the HTML code snippet: <div class="row header collapse"> Content 1 <i class="fas fa-chevron-circle-up" ></i> </div> <div class="instructions-container"> <div></di ...

Concealing content to prevent it from being accessed through HTML and JavaScript inspection techniques

I created a website with a simple guessing game where users can win if they enter the right code. My approach involves using JavaScript: <script> function z() { var b = document.getElementById('idea'); var a = document.g ...

Transferring information from the initiator to a pop-up window in Internet Explorer

I am looking to pass the scope and other values to a child window. It currently works as expected in Chrome, but not in Internet Explorer. Is there a workaround for this issue? var templateUrl = "/someviewpage"; var wOptions$ = 'menubar= ...

Learn the process of eliminating special characters from input or textarea fields with AngularJs!

My attempts to integrate an AngularJS directive to remove special characters from input and textarea fields have been unsuccessful. Despite no errors being reported in the console, I am facing issues with the character count tooltip not displaying numbers ...

Server vs Client-Side: Loading Dynamic HTML

Currently, I am working on a project that involves making AJAX calls to load hundreds of records from the database to be displayed on a slider. Specifically, the data I am retrieving includes the 'Image Path' for all the images, as well as other ...

What methods can be utilized to accurately determine a user's online status without continuously sending AJAX requests to the server through setInterval?

Seeking effective methods to determine a user's online status I am currently employing an inefficient technique to address this issue: I continuously send AJAX requests to the server at set intervals using setInterval, allowing the server to gauge th ...

Starting with NodeJS: Troubleshooting module not found error

I'm new to NodeJS and I'm following the guide on the official NodeJS site to create a server. I have successfully installed NodeJS on my computer and created an app.js file with the code below: const http = require('http'); const host ...

Guide on how to retrieve a server-generated message within a jQuery script on an EJS page

Is there a way to retrieve and utilize a variable passed from a controller to an EJS page in a jQuery script? Below is the code snippet for reference: app.get('/form', (req, res) => { res.render('form', { errorMessage: & ...

How to implement env.d.ts file in a Laravel 9 and Vite project?

Currently, I am in the process of setting up a new laravel project while drawing inspiration from element-plus-vite-starter. To initiate the new project, I used the following command: laravel new laravel-vue3 Afterwards, I proceeded to install all the ne ...

The slider causing conflicts with widgets and content positioned below it in an HTML layout

When implementing a slider with a fade effect, there seems to be an issue with the placement of widgets on the homepage. The problem arises from the margin-top setting as when images change in the slider, the widgets clash with the slider. During the trans ...

The Fetch API's Post functionality is currently experiencing issues

fetch('http://localhost:9000/api/app/contact', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: this.state.email, contactNumber: ...

unleashing the magic of AJAX: a guide to extracting

In my Symfony project, I am attempting to retrieve the content of an AJAX request in order to check the data using dump(). The purpose is to process this data and perform a SQL query. However, when I use dump() in my controller, there doesn't appear t ...

Revamping the login interface for enhanced user

Whenever I attempt to login by clicking the login button, there seems to be an issue as it does not redirect me to any other page. Instead, I am left on the same page where I initially clicked the button. The intended behavior is for users to be redirected ...

Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results. Initially, the following approach worked well: const value = 'TTest90()'; const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2 ...

Vue's lack of reactivity with props when storing values is a common issue

How can I ensure that the value passed using props updates in the child component's data when it changes in the parent? Is there a solution for this issue? Here is a link to a w3 test (I have tried to explain the problem as clearly as possible here) ...

Attempting to trigger the timer to begin counting down upon accessing the webpage

Take a look at this example I put together in a fiddle: https://jsfiddle.net/r5yj99bs/1/ I'm aiming to kickstart as soon as the page loads, while still providing the option to pause/resume. Is there a way to show the remaining time as '5 minute ...