简体   繁体   中英

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 i need to sort them by their age.

componentDidMount() {

    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>
    );

}

}

export default App;

This is what i got till now, i did the filter cause there's some characters that doesnt have known age, well, i guess i have to use a sort, something like

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

json item example:

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"

But idk how i have to exactly write it in my code and make it work, i have to make also a button where i can order from minor to major and to the reverse, thanks a lot if you can help me, i ve been with this all day yesterday, and sorry for not a perfect english, hope you can understand everything:P

Here you can find more information regarding sorting arrays in javascript.

You can chain some Array operations like sort and filter, so the solution would be to first filter out the characters without an age, and then sort the result:

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

This can then be used inside your JSX to display the characters without an age in order:

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>
);

Here is a working example to removing characters without an age and sorting ages in ascending and descending order:

 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>

Of course you will have to adapt the dataset and function to your own dataset in order for it to work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM