Search code examples
javascriptarraysjavascript-objectscity

JS how to return the amount of people that live in a city?


I'm new to coding and have been given this question but I cannot seem to make my code work. Dose anyone have any suggestions?

This is the question I have been given:

This function receives an array of people objects in for format:

[{ name: 'Sandra', lives: { country: 'UK', city: 'Manchester' }, age: 32 }]

The function should return the count of people who live in the city of Valencia

This is the code I have made;

function countPeopleInValencia(people) {
let count = 0
for (let i = 0; i < people.length; i++) {
  if (people.city[i] === 'Valencia') {
    count ++ }
  else {return 0}
  }
  return count
}

This is what my code will be run against;

describe("countPeopleInValencia", () => {
it("returns 0 when nobody is from Valencia", () => {
expect(
  countPeopleInValencia([
    {
      name: "Sandra",
      lives: { country: "UK", city: "Manchester" },
      age: 32
    },
    {
      name: "Sandrella",
      lives: { country: "Spain", city: "Bilbao" },
      age: 32.5
    }
  ])
).to.equal(0);
  });
  it("returns the length of the array when everyone is from Valencia",   () => {
  expect(
  countPeopleInValencia([
    {
      name: "Cassandra",
      lives: { country: "Spain", city: "Valencia" },
      age: 32.5
    },
    {
      name: "Cassandrella",
      lives: { country: "Spain", city: "Valencia" },
      age: 35.55
    }
  ])
).to.equal(2);
 });
it("returns the number of people who are actually from the fair city of Valencia", () => {
expect(
  countPeopleInValencia([
    {
      name: "Melissandra",
      lives: { country: "Spain", city: "Valencia" },
      age: 55.5
    },
    {
      name: "Melissandrella",
      lives: { country: "Spain", city: "Valencia" },
      age: 55.555
    },
    {
      name: "Keith",
      lives: { country: "UK", city: "Newport Pagnell" },
      age: 2
    }
  ])
).to.eql(2);
expect(
  countPeopleInValencia([
    {
      name: "Imeldarina",
      lives: { country: "Spain", city: "Valencia" },
      age: 15.2
    },
    {
      name: "Bob",
      lives: { country: "Wales", city: "Abertillery" },
      age: 555555555555.555
    },
    {
      name: "Terry",
      lives: { country: "England", city: "Newport Pagnell" },
      age: 0.00000002
    }
  ])
).to.equal(1);
});
});

Solution

  • In your current code you return the value of count as soon as you find a person who is not in the city you want to count

    function countPeopleInValencia(people) {
        let count = 0
        for (let i = 0; i < people.length; i++) {
            if (people.city[i] === 'Valencia') {
                 count ++ 
            }
        }
        return count
    }