Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
Find value in collection

I'm trying to figure out the following challenge:

Write a script in a programming language of your choice (I'm going with vanilla JS) that uses a loop and a conditional statement to find the value of the number of dogs in the following collection of key-value pairs. Depending on what language you’re using, it is acceptable to think of this variable as either a dictionary or an array of key-value pairs. Please only use logic that is native to the language without any external libraries:

KennelCapacity = {cats: 7, hamsters: 12, birds: 21, dogs: 3, chickens: 1}

I'm trying to set up a for loop with an if/else statement, but I'm honestly not sure how to piece it together for a proper answer. How should I do this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So, this question is very strange, because in JavaScript you could just do KennelCapacity.dogs and get the number of the dogs.
But this is not the question, so the following would be a possible solution:

const KennelCapacity = {
  cats: 7,
  hamsters: 12,
  birds: 21,
  dogs: 3,
  chickens: 1
};

let numberOfDogs;

// this gets [key, value] (here [animal, number]) of each key-value pair in the object
for (let [animal, number] of Object.entries(KennelCapacity)) {
  if (animal == "dogs") {
    numberOfDogs = number;
    break;
  }
}

console.log(numberOfDogs);

This code runs through your Object and gets each value-pair. (See Object.entries() at MDN).
With the Javascript notation [key, value] you can split the given array in the key and value or in my example code animal and value.

In the if statement is checked if the key is "dogs". If that is true, numberOfDogs is set to the number of dogs, that is stored as value in your object and the for loop is broken.

I hope, this helps you. If you have more questions, you are welcome to ask.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda