按字母顺序对 JS 循环获取的数据进行排序

问题描述 投票:0回答:3

我有一个程序,可以从 2 个获取的 URL 获取数据,使用 CSS,我自动创建名片类型设计,并在“for”循环中自动执行此操作。 现在我需要按“${users[count].name}”创建一个“按字母顺序排序”按钮,但我不知道如何做到这一点。

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>                      
            `

在此之后我有一些事件监听器,但我不认为它们很重要。我的想法是,我需要能够对打印的这些数据进行排序,但我不知道如何将它们全部存储在数组中,之后我考虑使用从 0 到 10 的“for”循环来输出它们结果是最低的数字或类似的数字。

javascript arrays json sorting
3个回答
0
投票

将逻辑拆分为函数。

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 class="profile_card">
        <div class="topCont">
            <img class="thumbnail" src="${photos[count].thumbnailUrl}">
            <div class="personal">
            <h2 class="name">${users[count].name}</h2>
        </div>   </div>   </div>`
  }
}
<button onclick="do_sort(); do_output()">sort</button>
<div id="names"></div>


0
投票

您应该将响应存储到数组中,然后操作它们对数据进行排序。

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>


0
投票
    sort.addEventListener("change",(e)=>{
    let copyArrClone = [...copyArrr];
    if (e.target.value == 'az') {
        let sortAz = copyArrClone.sort((a, b) => a.title.localeCompare(b.title));
        filteredArr = sortAz;
        getDataJson();
    } else if (e.target.value == 'za') {
        let sortZa = copyArrClone.sort((a, b) => b.title.localeCompare(a.title));
        filteredArr = sortZa;
        getDataJson();
    } else {
        getDataJson();
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.