簡體   English   中英

如何按年齡值對該數組進行排序?

[英]how can i sort this array by age value?

im studying right now and starting with reactjs and all that, i have to make a web page based in Game of thrones using an API, i recieve the api data and i can print in screen the img, name and age of the characters, but我需要按他們的年齡對他們進行分類。

組件DidMount() {

    fetch('https://api.got.show/api/show/characters/')
        .then(res => res.json())
        .then(json => {
            this.setState({
                items: json,
            })
        }).catch((err) => {
            console.log(err);
        });

}



render() {

    const {items} = this.state;
    

    return (
        <div className="App">
            <ul>
                {items.filter(item=> item.age && item.age.age).map(item => (
                    <li key={item.id}>
                    <img src={item.image} alt="personajes" ></img>  Name: {item.name} | age: {item.age.age}
                    </li>
                ))}
            </ul>
        </div>
    );

}

}

導出默認應用程序;

這就是我到現在為止得到的,我做了過濾器,因為有些角色不知道年齡,好吧,我想我必須使用一種排序,比如

items.sort((a,b) => a.item.age.age - b.item.age.age)

json 項目示例:

0   
titles  […]
origin  […]
siblings    […]
spouse  […]
lovers  []
plod    0
longevity   []
plodB   0
plodC   0
longevityB  []
longevityC  []
culture […]
religion    […]
allegiances […]
seasons []
appearances […]
_id "5cc0757c04e71a0010b86ac3"
name    "Eddard Stark"
slug    "Eddard_Stark"
image   "https://vignette.wikia.n…wn/323?cb=20160730050722"
gender  "male"
alive   false
death   298
father  "Rickard Stark"
house   "House Stark"
first_seen  "Winter Is Coming\""
actor   "Sean Bean"
related […]
createdAt   "2019-04-24T14:41:00.761Z"
updatedAt   "2019-04-24T14:41:00.761Z"
__v 0
pagerank    {…}
age :
name    "Eddard Stark"
age 60
id  "5cc0757c04e71a0010b86ac3"

但是我知道我必須如何在我的代碼中准確地編寫它並使其工作,我還必須制作一個按鈕,我可以在其中從次要到主要以及反向訂購,如果你能幫助我,非常感謝,我一直在昨天一整天,抱歉英語不是很完美,希望你能理解一切:P

在這里您可以找到有關在 javascript 中排序 arrays 的更多信息。

您可以鏈接一些數組操作,例如排序和過濾,因此解決方案是首先過濾掉沒有年齡的字符,然后對結果進行排序:

characters.filter(character => character.age).sort(compareFunction);

然后可以在 JSX 中使用它來按順序顯示沒有年齡的字符:

return (
  <div className="App">
    <ul>
      {items
        .filter(item => item.age && item.age.age)
        .sort((prev, next) => prev.age - next.age)
        .map(item => (
          <li key={item.id}>
            <img src={item.image} alt="personajes" ></img>  Name: {item.name} | age: {item.age.age}
          </li>
        ))}
    </ul>
  </div>
);

這是一個刪除沒有年齡的字符並按升序和降序對年齡進行排序的工作示例:

 function displayList(list) { let html = ''; for (const person of list) { html += `<li>${person.name}: ${person.age || "?"}</li>`; } document.getElementById('age-list').innerHTML = html; } const ageList = [{ name: "John", age: 12 }, { name: "Tim" }, { name: "Steven", age: 40 }, { name: "Marie", age: 50 }, { name: "Amy" }, { name: "Sheldon", age: 5 }, { name: "Charlotte", age: 25 } ]; displayList(ageList); document.getElementById('asc').onclick = () => { const ascList = ageList.filter(item=> item.age).sort((prev, next) => { return prev.age - next.age; }); displayList(ascList); } document.getElementById('desc').onclick = () => { const ascList = ageList.filter(item=> item.age).sort((prev, next) => { return next.age - prev.age; }); displayList(ascList); }
 <button id="asc">Ascending</button> <button id="desc">Descending</button> <ul id="age-list"></ul>

當然,您必須將數據集和 function 調整為您自己的數據集才能為您工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM