JS How to return an object from an array

  • A+
Category:Languages

I am new to coding and have been given this question;

Create a function that takes an array of people objects and returns the first found astronaut object from the array.

This is the code that I have created;

function findFirstAstronaut(people) {    for (let i = 0; i < people.length; i++) {      if (people.astronaut[i] === false) {        return null }      else  if (people.astronaut[i]) {        return people[i]      }     } 

My code is run against this test;

describe("findFirstAstronaut", () => {   it("returns null if no Astronaut is in the array", () => {     expect(findFirstAstronaut([])).to.be.null;   });    it("returns a person object who is an astronaut", () => {     const astronaut = { name: "Tim Peake", isAstronaut: true };      expect(findFirstAstronaut([astronaut])).to.have.keys([       "name",       "isAstronaut"     ]);     expect(findFirstAstronaut([astronaut]).isAstronaut).to.be.true;   });     it("returns the first astronaut from the array", () => {     const astronauts = [       { name: "Johnny Karate", isAstronaut: false },       { name: "Neil Armstrong", isAstronaut: true },       { name: "Valentina Tereshkova", isAstronaut: true },       { name: "Bert Macklin", isAstronaut: false },       { name: "Eileen Collins", isAstronaut: true },       { name: "Kip Hackman", isAstronaut: false }      ];      expect(findFirstAstronaut(astronauts)).to.eql({       name: "Neil Armstrong",       isAstronaut: true     });   }); }); 

Dose any one have an idea of how to fix my code?

 


You need to use the index for the array.

people[i]                // for the object people[i].isAstronaut    // for a property of the object 

Then you need only a check if isAstronaut is true and return with the item.

At the end outside of the for loop, return null, for a not found astronaut.

If you check inside the loop, you will return too early with the wrong result.

function findFirstAstronaut(people) {     for (let i = 0; i < people.length; i++) {         if (people[i].isAstronaut) {             return people[i];         }     }     return null; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: