Arrange Data Alphabetically using a JavaScript Loop

I have a unique program that extracts data from 2 different URLs. Using CSS, I automatically generate a sleek Business Card design in a 'for' loop. Now, I'm faced with the challenge of creating a Sort Alphabetical button based on "${users[count].name}" and frankly, I'm stumped on how to tackle this.

Promise.all([
    fetch('https://jsonplaceholder.typicode.com/photos'),
    fetch('https://jsonplaceholder.typicode.com/users')
]).then(function (responses) {
    return Promise.all(responses.map(function (response) {
        return response.json();
    }));
}).then(([ photos , users]) =>{
    var names = document.getElementById('names')
    for (let count = 0; count < 10; count++){
        names.innerHTML+=`
        <div class= "profile_card">
        <div class=topCont>
            <img class="thumbnail" src="${photos[count].thumbnailUrl}">
           
            <div class="personal">
            
                        <h2 class="name">${users[count].name}</h5>
... etc
</div>   </div>                      
            `

Following that, there are some EventListeners involved, but I don't believe they are relevant to my current dilemma. The main issue at hand is figuring out how to organize and store all the printed data in an Array so that I can implement a sorting mechanism. One idea that crossed my mind is utilizing a 'for' loop from 0 to 10 to display them based on ascending order or another criteria.

Answer №1

Organize your code by breaking it down into functions.

var array_photos;
var array_users;

Promise.all([
  fetch('https://jsonplaceholder.typicode.com/photos'),
  fetch('https://jsonplaceholder.typicode.com/users')
]).then(function(responses) {
  return Promise.all(responses.map(function(response) {
    return response.json();
  }));
}).then(([photos, users]) => {
  array_photos = photos; 
  array_users = users;
  display_output(array_photos, array_users)
})


function sort_data() {
  array_users.sort(function(a, b) {
    if (a.name > b.name) {
      return 1;
    }
    if (a.name < b.name) {
      return -1;
    }
    return 0
  })
}

function display_output() {
  photos = array_photos
  users = array_users;

  var names_section = document.getElementById('names')
  names_section.innerHTML = '';
  for (let index = 0; index < 10; index++) {
    names_section.innerHTML += `<div class="profile_card">
        <div class="topCont">
            <img class="thumbnail" src="${photos[index].thumbnailUrl}">
            <div class="personal">
            <h2 class="name">${users[index].name}</h2>
        </div>   </div>   </div>`
  }
}
<button onclick="sort_data(); display_output()">Sort</button>
<div id="names"></div>

Answer №2

To properly manage your responses, it is recommended to save them in an array and then apply manipulations to organize the information.

const loadDataButton = document.getElementById('loadDataButton')
const sortByUserName = document.getElementById('sortByUserName')
const sortByAlbumName = document.getElementById('sortByAlbumName')

let users = []
let albums = []

loadDataButton.addEventListener('click', async () => {
  await fetch('https://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(data => users = data)
  
  await fetch('https://jsonplaceholder.typicode.com/albums')
  .then(res => res.json())
  .then(data => {
    albums = data.map(x => ({...x, user: users.find(user => user.id === x.userId)}))
  })
 
  displayAlbums()
})


function showAlbums(){
  const app = document.getElementById('app')
  
  app.innerHTML = '' //clear
  
  albums.forEach(album => {
    const p = document.createElement('p')
    p.innerHTML = `${album.title} - ${album.user.name}`
    app.appendChild(p)
  }) 
}


sortByUserName.addEventListener('click', () => {
  albums.sort((a, b) => {
    if(a.user.name > b.user.name) return 1
    else return -1
  })
  
  displayAlbums()
})

sortByAlbumName.addEventListener('click', () => {
  albums.sort((a, b) => {
    if(a.title > b.title) return 1
    else return -1
  })
  
  displayAlbums()
})
<button id="loadDataButton">Load data</button>

<button id="sortByUserName">Sort by user name</button>
<button id="sortByAlbumName">Sort by album name</button>

<div id="app"></div>

Answer №3

    document.getElementById("sort").addEventListener('change', event => {
        let clonedArray = [...originalArray];
        if (event.target.value == 'ascending') {
            let sortByAsc = clonedArray.sort((a, b) => a.title.localeCompare(b.title));
            filteredData = sortByAsc;
            fetchData();
        } else if (event.target.value == 'descending') {
            let sortByDesc = clonedArray.sort((a, b) => b.title.localeCompare(a.title));
            filteredData = sortByDesc;
            fetchData();
        } else {
            fetchData();
        }
    })

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

Discovering the properties in an object using a variable name in JavaScript

I am sending my string to the function below. $scope.sort= function(query){ console.log(query); // returns "name"; $scope.resultset.sort(function(a, b) { return parseFloat(b.query) - parseFloat(a.query); //returns undefined; }); }; wher ...

Animating pseudo-elements using Jquery

I'm having trouble animating the :after pseudo-element of my ul. Below is the CSS code I have: #slider .mypagination ul::after { content: ""; width:25%; bottom: 0; left:0; position: absolute; border-top:1px solid #7accc8; ...

Retrieving additional links on a webpage by making JSON requests using Python

As I extract links from a specific box with infinite scroll on a website, I am utilizing the following code to send requests for obtaining the next set of 10 links: import requests from bs4 import BeautifulSoup import urllib2 import urllib import extracti ...

JQuery Mobile fails to apply consistent styling to user input check items within a list

I have successfully implemented the functionality to add user input items to a checklist. However, I am facing an issue where the newly added items are not adhering to Jquery Mobile's styling. Here is a screenshot showcasing the problem: Below is th ...

Are there any alternatives to PHP for implementing an auto-complete search feature?

I have decided to focus on using HTML, MySQL, JavaScript, and jQuery for my project. Though I understand that learning PHP would be beneficial in the long run, I don't have enough time to master it all within a week. As for the server-side, I will be ...

The problem with Vue JS static links

I'm currently working with a Vue.js application (v2). I've noticed that if I skip visiting the root of the site, the sub-links do not work properly. For example: Visit: Then go to If I directly visit: I encounter the following error messag ...

Eliminate the listener if the connected function contains a binding

Here is a code snippet to consider: class Test { constructor() { this.breakpoints = {}; } add(options) { // Register the media query this.breakpoints[options.breakpoint] = window.matchMedia(options.breakpoint); ...

Enhancing Material UI icons with a sleek linear gradient

Despite following the instructions in this post Attempting to incorporate a linear gradient into a MaterialUI icon, as per a comment's recommendation, I am unable to get it to work. I experimented with the idea that the icons could be considered text ...

Learn how to find and filter elements in arrays that do not include a particular value using React

In my collection of recipes, I have the ability to filter out the ones that include specific ingredients. However, when I attempt to reverse this process by using .some method, it only checks the first item in the array. Here is an example of my data stru ...

How can I adjust the animation speed for ChartJS graphics?

Trying to adjust the animation speed of a pie chart in chartJS. Various methods have been attempted: numSteps: Number animationSteps: Number Chart.defaults.global.animationSteps = Number However, none of these approaches have successfully altere ...

``What is the process for retrieving an object array that has been stored in a session using

I have a new class definition: class ProductDetails { name!: string; price!: number; } I keep an array of these objects in the local storage like this: productList: Array<ProductDetails> = []; ... ... localStorage.setItem("CurrentProducts ...

The ios browser environment is unable to retrieve the value during vuejs development

When using vuejs components to create a countdown component, everything seems normal in the pc and Android environments. However, in the iOS environment, there seems to be an issue with obtaining the real count calculation as it returns NaN. <templ ...

PHP unset() having issues with selective removal

I have come across various unset() issues on this platform, but the one I am facing is unique. My goal is to create an array that excludes certain file names from a directory listing, specifically ".", "..", "feed.txt", and "index.php". Below is the code s ...

Having trouble with jQuery Animate when trying to change the background-color property?

So, I was experimenting with the jQuery .animate() function and decided to change the background color of a div based on how many pixels the user scrolled. Surprisingly, it didn't work as expected. After switching to the .css() function instead, every ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

Trigger a JavaScript function on a body click, specifically targeting certain elements to be excluded

I have a dropdown menu within a div element. I've created a javascript function called HideDropdown() that hides the menu when any main link on the page is clicked, except for links within the dropdown menu itself: <script> function HideDropdow ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...

The error message "ECONNRESET" occurred while attempting to send a post request using Axios to

Attempting to send a post request to my webserver using axios, I have a client that collects user input to populate an array of strings. This data is then sent via a post request using axios for processing by the server: if (parsedInput > 0 &&am ...

Step-by-step guide for adding an icon to the corner of a Material UI button

Is there a way to position an icon in the corner of a Material UI button in React? Currently, I have the icon next to the title but I would like to move it to the lower right corner of the button. Any suggestions on how to achieve this? Thank you! export ...

Utilizing various filters with JQ

My supervisor wants our team to utilize JQ for parsing JSON files. The application I am using generates JSON data that requires transformation. Below is an example of the file structure: { "Collections": [ { "OptionGroups": [ ...