Function userHasVisitedAllParksInState

const parks = [
    {
      id: 1,
      name: "Acadia",
      areaInSquareKm: 198.6,
      location: { state: "Maine" },
    },
    {
      id: 2,
      name: "Canyonlands",
      areaInSquareKm: 1366.2,
      location: { state: "Utah" },
    },
    {
      id: 3,
      name: "Crater Lake",
      areaInSquareKm: 741.5,
      location: { state: "Oregon" },
    },
    {
      id: 4,
      name: "Lake Clark",
      areaInSquareKm: 10602,
      location: { state: "Alaska" },
    },
    {
      id: 5,
      name: "Kenai Fjords",
      areaInSquareKm: 2710,
      location: { state: "Alaska" },
    },
    {
      id: 6,
      name: "Zion",
      areaInSquareKm: 595.9,
      location: { state: "Utah" },
    },
  ];

  const users = {
    "karah.branch3": {
      visited: [1],
      wishlist: [4, 6],
    },
    "dwayne.m55": {
      visited: [2, 5, 1],
      wishlist: [],
    },
    thiagostrong1: {
      visited: [5],
      wishlist: [6, 3, 2],
    },
    "don.kim1990": {
      visited: [2, 6],
      wishlist: [1],
    },
  };

I need to write a function userHasVisitedAllParksInState that does: This function returns a boolean that represents whether or not a user has visited all parks in the parks array from a given state.

I don’t have any code for this because I don’t even know where to start. Every time I think I have an idea it falls apart. Any help is appreciated.

function userHasVisitedAllParksInState(parks, users, state, userId) {}

Answer

You have a lot of ways you can solve this, but here are two ideas that you can continue developing:

One solution is very simple that works if you can’t have visited the same park more than once. Create a list of the parks that match the requested state and check if the length of that is the same as the number of parks the person visited.

function userHasVisitedAllParksInState(parks, users, state, userId) {
  var parksForState = parks.filter((park) => park.location.state === state);
  return users[userId].visited.length === parksForState.length;
}

Another solution that might be easier to understand and works even if you have duplicate entries in the visited arrays:

function userHasVisitedAllParksInState1(parks, users, state, userId) {
  var user = users[userId];
  var parksForState = parks.filter((park) => park.location.state === state);
  // Assume the person did visit all to start
  var visitedAll = true;
  for (var i = 0; i < parksForState.length; i++) {
    // If the park we're checking atm is in the visited array, we've still visited all parks. If parksForState[i].id is not in user.visited
    visitedAll = visitedAll && user.visited.indexOf(parksForState[i].id) > -1;
  }
  return visitedAll;
}

Leave a Reply

Your email address will not be published. Required fields are marked *