Home > Back-end >  Sort Alphabetically JS Loop with Fetched Data
Sort Alphabetically JS Loop with Fetched Data

Time:08-01

i have a program that gets data from 2 fetched URLs, with CSS I automatically create a Business Card type design and it does that automatically in a 'for' loop. Now I need to create a Sort Alphabetical button by that "${users[count].name} and I do not have any idea how to do that.

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  src="${photos[count].thumbnailUrl}">
           
            <div >
            
                        <h2 >${users[count].name}</h5>
... etc
</div>   </div>                      
            `

After this i have some EventListeners but I do not this they matter. The idea is that i need to be able to sort these data that I print but I do not know how to store all of them in an Array and after that I thought about using a 'for' loop from 0 to 10 to output them by the number that resulted to be the lowest or something like that.

CodePudding user response:

Split your logic into functions.

var arr_photos;
var arr_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]) => {
  arr_photos = photos; 
  arr_users = users;
  do_output(arr_photos, arr_users)
})


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

function do_output() {
  photos = arr_photos
  users = arr_users;

  var names = document.getElementById('names')
  names.innerHTML = '';
  for (let count = 0; count < 10; count  ) {
    names.innerHTML  = `<div >
        <div >
            <img  src="${photos[count].thumbnailUrl}">
            <div >
            <h2 >${users[count].name}</h2>
        </div>   </div>   </div>`
  }
}
<button onclick="do_sort(); do_output()">sort</button>
<div id="names"></div>

CodePudding user response:

You should store your responses into array and then manipulate them to sort the data.

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)}))
  })
 
  showAlbums()
})


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
  })
  
  showAlbums()
})

sortByAlbumName.addEventListener('click', () => {
  albums.sort((a, b) => {
    if(a.title > b.title) return 1
    else return -1
  })
  
  showAlbums()
})
<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>

  • Related