sorting an array in ascending and descending order using Javascript

I have been experimenting with arrays and created two buttons - PushUP and PushDown. The purpose of the PushUp button is to sort the array in ascending order, while the PushDown button sorts it in descending order. Despite my efforts, I have not been able to achieve the desired outcome. Can someone assist me on what code I need to write to obtain the following output? Additionally, how can I display this data before any Push button is clicked and then change the order based on the button clicked? For instance, initially displaying 2 buttons along with the data.

Upon clicking the mentioned buttons, the output should resemble something like this:

Original array:

1 xyz
2 abc, 123
3 asd

On clicking PushUp:

3 asd
1 xyz
2 abc, 123

On clicking PushDown:

1 xyz
2 abc, 123
3 asd

Here is a section of my code:

var details = [
{intro: "ABC"},
{due: " MON"},
{name: "XYZ", sn: "SN xxxxx"},
{lab: "Tuesday 4:30-6:30"}
];
function Push_Up(){
   details.sort();
   displayPUSH();
}
function displayPUSH() {
    document.getElementById("up").innerHTML =
    "<br>" +
    "CSIT128" + " :" + details[0].intro + "<br><br>"      + 
    "Assignment 5"+ ", " + details[1].due   + "<br><br>"    +
     details[2].name + ", " + details[2].sn + "<br><br>" +
    "Computer LAB" + " :" + details[3].lab + "<br><br>";
 }
 function Push_Down(){
    var details_after ="";
    for ( var i=0; i<details.length; i++ )
    {
        displayPUSH(); 
    } 
    document.getElementById("down").innerHTML = details_after;
 }
<button onClick="Push_Up()"> Push Up </button>
<br>
<div id="up">
</div>

<button onClick="Push_Down()"> Push Down </button>
<br>
<div id="down">
</div>
<br>

Answer №1

If you want to implement a circular shift function, consider the following method:

let elements = [
  'apple',
  'banana',
  'orange'
];

function display() {
  document.getElementById('output').innerHTML = elements.map(item => `<li>${item}</li>`).join('');
}

document.getElementById('move-up').addEventListener('click', function() {
  const firstElement = elements.shift();
  elements.push(firstElement);
  display();
});

document.getElementById('move-down').addEventListener('click', function() {
  const lastElement = elements.pop();
  elements.unshift(lastElement);
  display();
});

display();
<button id="move-up">Move Up</button>
<button id="move-down">Move Down</button>
<ul id="output"></ul>

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

The JsFiddle code is malfunctioning

One question I have is about preparing a JSFiddle for a small click program which is not working. It consists of just two lines of code. HTML <body> <button onclick="javascript:launchdialog();">Click Me</button> </body> JavaS ...

Troubles encountered when creating select/drop-down optgroup using jquery

Looking to incorporate the <optgroup> tag into a dropdown with JQuery. The option works as expected, but struggling with getting the option group to function correctly. Here's the HTML setup: <select name="DropDownID" id="DropDownID"> ...

Steps to make background color transparent in Phaser 3

Issue I encountered a problem when adding two Text objects to a scene. The background color of the latter one could not be set to transparent. Is there anyone who can assist me with this? Below is a screenshot for reference. Attempted Solutions I at ...

MongoDB Integration of Collections - No Data Population

Having trouble merging a client and an account collection. When I use res.send(client), only the account id's are returned. Unsure how to include account information in clients. Have seen one to many solutions, but struggling with this two-way relati ...

What's the best way to manage the onClick event for individual input submit types using jQuery?

As a novice in jQuery, I am still in the learning phase. However, I urgently require a solution to set up a click event registration for each button within my table. The table below is created using GridView: <div id="gridView"> &l ...

Achieving accurate JSON output from Elasticsearch's autosuggest feature can be

Running my node.js server involves sending queries to an elasticsearch instance. I have a JSON example of the query's output: { "took": 2, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 ...

Button to scroll down

I have successfully implemented a #scrolldownbutton that scrolls to the first component. However, I am now attempting to modify it so that when the button is clicked, the page smoothly scrolls within the viewport and stops at the partially visible componen ...

What is preventing me from accessing the hidden article using the URL with the hashname?

I've been searching for a solution, but so far nothing seems to work for me. I have a page with header and content sections. The content section is currently not visible. When I click on an item in the navigation menu, I want to hide the header and di ...

Using Next-auth.js: Redirecting from getServerSideProps to a specific callback URL - How can it be done?

Hey, I've been working on implementing authentication with the NextAuth library in my Next.js application. While following the documentation, I encountered a situation that wasn't covered. I'm attempting to create a 'route guard' o ...

Which is better for toggling between images/icons: a switch statement or a ternary operator?

I have a unique challenge where I am dealing with a dynamic list of thumbnails. Some of the items in this list are images, while others need to be represented by icons. My goal is to display either an image or an icon based on the contentType of each item. ...

Inquiry regarding the setTimeout function requiring an answer

I have a question about how setTimeout works. Does it wait for the previous code to finish executing before moving on to execute something else after a set time, or does it simply wait for a specific amount of time and then continue with the rest of the co ...

JavaScript GridView

Is there a way to determine if an ASP.NET GridView contains at least one row by using JavaScript? ...

Improving functions in vue.js

Currently working on my personal project, which is an HTML website containing tables generated through vue.js. I believe that my code could be simplified by refactoring it, but I am unsure about where and what changes to make. Below is the section of the c ...

Steps for toggling the visibility of an input field of type text upon clicking a button

message button <div id="messagebutton" class="btn4 like" style="margin-top:-25px;margin-left:-10px;"> <span class="btn reply" id="messageb">Message</span> </div> text box <div class="col-lg-12" style="background:#eff9c7;" ...

React Native - Issue with array value not reflecting in Text component

import React, {useState} from 'react'; import { FlatList, Text, View} from 'react-native'; import {styles, styleBox} from './components/styles'; import Slider from '@react-native-community/slider'; export default fu ...

Generating procedural textures for particles within the context of three.js

I am working towards creating a particle system that involves procedurally generated textures for each particle's vertices. However, I am facing challenges in developing a prototype that can function seamlessly under both the Canvas and WebGL renderer ...

I'm facing an issue while attempting to fetch an API. I'm not certain what is lacking in my code, but the console is showing an error on

While troubleshooting my code, the console pointed out an error in line 15 of my javascript. However, I am having trouble identifying what exactly is causing the issue. The button I designed in HTML does not seem to be fetching the API facts as intended, ...

Prevent background music from being manipulated

I've implemented an audio HTML element with background music for a game: <audio class="music" src="..." loop></audio> However, I have encountered an issue where upon loading the page, I am able to control the music usi ...

When new text is added to Div, the first line is not displayed

One of the divs on my page has an ID of "TrancriptBox" and contains multiple lines of text. When I scroll through it on my iPad, everything works fine. However, if I scroll and then change the text within that div, it doesn't display the first line o ...

Utilize Jquery to send a preset value through an ajax request

I am working on a select box functionality where the selected option is sent via ajax to a server-side script. The current setup is functioning properly. Here is the code for the select box: <select id="main_select"> <option selecte ...