JavaScript: Reorder an array to alternate between largest and smallest elements, starting with the largest

When working with an array of integers that need to be sorted in a specific order, such as:

[1, -1, -3, 9, -2, -5, 4, 8,]

We must rearrange them so that the largest number is followed by the smallest number, then the second largest number followed by the second smallest number, and so on.

[9, -5, 8, -3,  4, -2, 1, -1 ]

While it's clear how to find the first largest and smallest numbers manually, making this process dynamic for all values in the array can be more challenging.

One approach involves using two variables, such as firstSmallest and firstLargest, pointing to the first and last index of the sorted array. By iterating through the array, we can increment firstSmallest and decrement firstLargest to store the desired arrangement into a new output array.

let unsortedArr = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]

let output = [];

function meanderArray(unsorted){
  let sorted = unsorted.sort((a, b) => a-b);
  let firstSmallest = sorted[0];
  let firstLargest = sorted[unsorted.length-1];

  for(let i = 0; i <= sorted.length; i++){
  //Increment firstSmallest and decrement firstLargest to generate the desired output
  } 
 return output;
}
meanderArray(unsortedArr);
console.log(output);

Answer №1

You can utilize a toggle object to select either the first or last property from an array and continue iterating until there are no more items left.

function alternateArray([...array]) {
    const 
        result = [],
        toggle = { shift: 'pop', pop: 'shift' };

    let fn = 'shift';

    array.sort((a, b) => a - b);

    while (array.length) result.push(array[fn = toggle[fn]]());

    return result;
}

console.log(...alternateArray([1, 5, 8, 7, 6, -1, -5, 4, 9, 5]));

Answer №2

If you want to arrange an array in descending order, here's a neat logic for you: start by taking the first element from the beginning and the end of the array, then move on to the second element from the beginning and the second-to-last element, and so forth.

let nums = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]

let arrangedArray = [];

function meanderTheArray(arr){
  let sortedArr = arr.sort((a, b) => b-a);
  let result = []

  for(let index = 0; index < sortedArr.length/2; index++){
    result.push(sortedArr[index])
    if(index !== sortedArr.length - 1 - index){
      result.push(sortedArr[sortedArr.length - 1 - index])
    }
  } 
 return result;
}
let finalResult = meanderTheArray(nums);
console.log(finalResult);

Answer №3

To organize the data, you can first sort it and then use pop() to extract the last number and shift() to retrieve the first number.

let unsortedArr = [1, -1, -3, 9, -2, -5, 4, 8,]
let output = [];

function rearrangeArray(unsorted){
    let sorted = unsorted.sort((a, b) => a - b);

    for(let i = 0; i < unsortedArr.length + 2; i++){
        output.push(sorted.pop());
        output.push(sorted.shift());
    } 
console.log(output);
return output;
}

rearrangeArray(unsortedArr);

Answer №4

Revolutionary Meandering Array technique outperforming all previously mentioned solutions.

Based on the results from JSBench.me, this approach stands out as the fastest, supported by a screenshot provided below for your convenience.

While devising my own method for creating a Meandering Array, I stumbled upon an approach that closely resembles the solution proposed by elvira.genkel.

In my implementation, I began by sorting the input array and identifying its midpoint. Subsequently, I divided the sorted array into two subsets: one spanning indices from 0 to the middle index and the other covering from the middle index to the end of the sorted array.

To prevent encountering undefined values in the resulting array due to unequal lengths of the subarrays during the subsequent for() loop iteration, I took care to increment the length of the first subarray by one.

Hence, it is crucial to ensure that firstArr.length > secondArr.length at all times.

The objective was to generate a new array with elements arranged in a meandering fashion. To achieve this, I utilized a for() loop to interleave values from the beginning of the first subarray with those from the end of the second subarray, ensuring that the dynamically calculated index for the latter remains non-negative. Any negative index would introduce unwanted undefined values into the resulting Meandering Array.

This optimized solution aims to benefit coding enthusiasts who seek high-performance implementations :)

Your feedback and suggestions are highly appreciated.

const unsorted = [1, 5, 8, 7, 6, -1, -5, 4, 9, 5];
const sorted = unsorted.sort((a,b)=>a-b).reverse();
const half = Math.round(Math.floor(sorted.length/2)) + 1;
const leftArr = sorted.slice(0, half);
const rightArr = sorted.slice(half, sorted.length);
const newArr = [];

for(let i=0; i<leftArr.length; i++) {
 newArr.push(leftArr[i]);
 if (rightArr.length-1-i >= 0) {
   newArr.push(rightArr[rightArr.length-1-i]);
 }
}

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

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

Upgrade button-group to dropdown on small screens using Bootstrap 4

I am currently developing a web application and incorporating Bootstrap 4 for certain components such as forms and tables. Within the design, I have included buttons grouped together to display various actions. Below is an example code snippet: <li ...

Looking for a way to upload only part of a large file using HTML and PHP

Is it possible to create a PHP script that can upload only the first 1 MB of a very large file? Can this be achieved with a standard form upload in PHP by closing off the connection after 1 MB is uploaded? I have researched various uploaders (HTML5/Java ...

Using a UUID as the default ID in a Postgres database system is a straightforward process

As I transition to postgres from mongodb due to the recent announcement, I've noticed that the IDs are simply numerical and auto-incremented. I've attempted a few solutions: Setting the default ID to a UUID with a lifecycle hook - Unfortunately, ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

Invoke functions within a separate function

I am facing an issue when it comes to invoking functions within another function. Below is a snippet of the code I am working with: <script> function saveInfo() { function returnEmail() { var _e = document.getElementById("em ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

Is there a way for me to generate a preview thumbnail for my video?

Looking to add a preview effect to video thumbnails when users hover over them, displaying a series of frames from the video. Are there any jQuery plugins or tutorials available for creating this effect? ...

Transfer the information of a selected element to a different element

Hello, I am trying to transfer content from a child element to another element. In my HTML setup, there is a hidden div named "DetailsExpanded" and multiple items called "IconWrapper". When an "IconWrapper" is clicked, I want to copy the content of its "I ...

Displaying properties of objects in javascript

Just starting with JavaScript and struggling to solve this problem. I attempted using map and filter but couldn't quite implement the if condition correctly. How can I find the records in the given array that have a gender of 0 and color is red? let s ...

Failed to fully install all dependencies for my project with yarn install

After cloning a project from gitlab, I attempted to install the dependencies using the yarn install command. However, there are several dependencies that yarn is unable to install and it keeps showing the error message: info There appears to be trouble wit ...

Vite terminal not executing Npm commands

Here is what I entered: npm run dev Error: npm ERR! Missing script: "dev" npm ERR! npm ERR! To see a list of scripts, run: npm ERR! npm run npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\andre\AppData&bs ...

Tips for populating individual arrays in AngularJS with data from a JSON:- Iterate through the JSON

I am attempting to extract each data from a JSON file and store it in a new array, as I want to create a graph. However, the process is not working as expected. Here is what I expect: f = { "FAKULTAS":"01/FKIP", "FAKULTAS":"02/FMIPA", "FAKULT ...

Determining when props are updated in Vue.js 2 when passing an object as a prop

Let's say there is an array feedsArray, with a sample value like this: this.feedsArray = [ { id: 1, type: 'Comment', value: 'How are you today ?' }, { id: 2, type: 'Meet', name: 'Daily ...

Angular single page application with a sleek, user-friendly navigation bar for easy browsing

I have been attempting to solve the issue at hand without much success. As a newcomer to web development, I have been working on creating a basic app using angularjs and bootstrap. My pages are fairly sparse, consisting only of a few inputs and buttons t ...

The CKEditor value is set to the result of the dropdown selection

I need to implement a dropdown feature on my form where the options correspond to titles of content in my database. Once an option is selected, I want the corresponding content to display in a CKEditor field. I'm attempting to achieve something simil ...

Messages and responses from an array within a discord.js bot

Currently, I am attempting to set up my discord.js version 12.0.0 bot to react to specific words using arrays for words and corresponding responses. However, I am encountering the following error message: TypeError: Cannot read property 'split' o ...

Learn the technique of initiating one action from within another with Next Redux

I'm looking to set up user authorization logic when the page loads. My initial plan is to first check if the token is stored in the cookies using the function checkUserToken. Depending on whether the token is present or not, I will then call another f ...

Create a search feature using Javascript and React that retrieves and displays results from a

I am currently developing a React application with a search feature that fetches JSON data and displays matching search results on the website import { React, useState } from 'react'; export default function PractitionerSearch() { const [data ...

Discovering the exact distance between a 'li' and a 'div' element

Currently, I am in the process of converting HTML to JSON. Here is an example of the HTML I am working with: <div class="treeprofit" id="divTreeViewIncomeDetails" style="height: auto;"> <li><span class="fa fa-folder-open highlight" ...

Nesting objects within arrays using Typescript Generics

Hello, I am currently attempting to assign the correct type to an object with nested values. Here is a link to the code in the sandbox: https://codesandbox.io/s/0tftsf interface Product { name: string, id: number productList?:ProductItem[] } interf ...