3

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

Fran Ruiz
  • 33
  • 5
  • 1
    Can you please add example data? – Rajesh Dec 08 '20 at 10:53
  • @Rajesh There's some character, for example, Eddard Stark does have 60 years old, Robb Stark 33, so in the page should appears first Robb Stark and so – Fran Ruiz Dec 08 '20 at 10:57
  • Please add a sample of `items` array to the question in a JSON format. – adiga Dec 08 '20 at 11:04
  • Does this answer your question? [Sorting object property by values](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) – angel.bonev Dec 08 '20 at 11:08

1 Answers1

1

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.

Titulum
  • 9,928
  • 11
  • 41
  • 79
  • They already know how to sort. `items.sort((a,b) => a.item.age.age - b.item.age.age)` Their issue is *"some characters that doesnt have known age*" – adiga Dec 08 '20 at 11:15
  • exactly, i know how to sort, my problem is that in that database there's some characters without age, that's why i used this filter {items.filter(item=> item.age && item.age.age) with that filter all the characters appears and avoid the ones without age, but idk how to insert the sort in the code i already have. – Fran Ruiz Dec 08 '20 at 11:19
  • I've updated my answer to take in account objects without an age property. – Titulum Dec 08 '20 at 11:23
  • The thing is that i can't print a character without age, so cant be a character printed that doesn't have an age. :S but thanks for this answer. – Fran Ruiz Dec 08 '20 at 12:26
  • I'm not really understanding your problem. You want to filter out characters without an age, and then sort the remaining characters by age? – Titulum Dec 08 '20 at 12:28
  • I've updated my answer to solve that problem. – Titulum Dec 08 '20 at 12:34
  • hey, so you are saying i can add a sort inside this? im gonna try, but im really lost right now, idk how exactly do it, i think i'm super blocked right now {items.filter(item=> item.age && item.age.age).map(item => ( – Fran Ruiz Dec 08 '20 at 17:52
  • Yes, you can [chain array methods](https://gomakethings.com/chaining-array-methods-in-vanilla-js/). So it should be like this: `charachters.filter.sort.map`. I'm not at my computer at the moment, but when I get back I'll add some more information. – Titulum Dec 08 '20 at 18:20
  • I have added a react example in my answer – Titulum Dec 09 '20 at 08:46
  • YES! this worked, that was my problem, didnt know how to exactly write it, thanks A LOT. – Fran Ruiz Dec 09 '20 at 15:27