1

I'm new to JavaScript. I'm trying to do the following could someone help please

  1. Fetch the list of people from the above URL
  2. Print the name of the youngest female
    import "./styles.css";
    
    const url = "https://randomuser.me/api/?results=10&seed=10&inc=name,gender,dob";
    
    
    
    fetch(url)
      .then((response) => {
        return response.json();
      })
      .then((myJson) => {
        console.log(myJson);
      });
    document.getElementById("app").innerHTML = `
    <p>
      Youngest female: 
    </p>
    `;
7
  • What is the format of your data? Can't you sort it, for example JavaScript: Sort an array of objects by a numeric property in each object Commented May 19, 2021 at 5:50
  • @VLAZ Its with DOB not age. I'm not sure how to sort it Commented May 19, 2021 at 5:54
  • 1
    You need to have document.getElementById("app").innerHTML inside the then callback. Check the duplicate on how to get the object with max DOB property Commented May 19, 2021 at 5:55
  • Are you not able to get the list of people from the api call already? I guess you just want to get the youngest person, right? Commented May 19, 2021 at 5:58
  • @WahabShah Yes, i just want to print the youngest female. Using fetch i did console.log and was able to get the data. BUt i'm not sure about printing it tho Commented May 19, 2021 at 6:01

1 Answer 1

0

You just need to manipulate the data to get the youngest female

  • First get all females
  • Get the first female to compare with using array index females[0]
  • Compare it will all other females and store the result in result
  • Add text to HTML in the then block itself.

const url = "https://randomuser.me/api/?results=10&seed=10&inc=name,gender,dob";

fetch(url)
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    const arr = myJson.results;
    const females = arr.filter((o) => o.gender === "female");
    let result = females[0];
    console.table(females);
    for (let obj of females) {
      if (obj.dob.age < result.dob.age) {
        result = obj;
      }
    }
    const {
      name: { title, first, last }} = result;
    document.getElementById(
      "app"
    ).innerHTML = `<p>Youngest female: ${title} ${first} ${last}</p>`;
  });
<div id="app"></div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.