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>
    `;
Sifat Moonjerin
  • 155
  • 1
  • 11
blake
  • 13
  • 3
  • 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](https://stackoverflow.com/q/54623130) – VLAZ May 19 '21 at 05:50
  • @VLAZ Its with DOB not age. I'm not sure how to sort it – blake May 19 '21 at 05: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 – adiga May 19 '21 at 05: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? – Wahab Shah May 19 '21 at 05: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 – blake May 19 '21 at 06:01
  • there's several ways, here's one - https://jsbin.com/tapubes/4/edit?js,output – balexandre May 19 '21 at 06:12
  • let item = Math.min(...result.results.filter(x=>x.gender=='female').map(function(x){return x.dob.age})); var user= result.results.find(x=>x.dob.age==item) This will give the the youngest female details – Rahul Shukla May 19 '21 at 06:24

1 Answers1

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>
decpk
  • 6,314
  • 1
  • 10
  • 24