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

216
Visualizações
Javascript object returning {} when filling

I was taking an online assessment, and I cannot figure out why my original solution in JS was not working. My first solution is contained in the top two function calls. No matter what, it returned an empty object {}. When I copy and pasted the function body from findOrderQuantity into allCandyOrders, it worked just fine.

function findOrderQuantity(candyObject) {
  if (candyObject.inStock < candyObject.weeklyAverage) {
    return 2 * candyObject.weeklyAverage;
  } else {
    return 0;
  }
  return 0;
}


function allCandyOrders(inventory) {
  // this function fails, and always returns {}
  let orderSet = {};
  let quantity = 0;
  let name = '';
  for (let i = 0; i < inventory.lengh; i++) {
    // compute how many to order
    quantity = findOrderQuantity(inventory[i]);
    // add candy to object
    // inventory[i].candy is a string containing a candyName
    name = inventory[i].candy;
    orderSet[name] = quantity;
  }

  return orderSet;
}

Working code

function allCandyOrders(inventory) {
  // this function works properly.
  let orderSet = {};
  let value = 0;
  let candyObject = inventory[0];
  for (let i = 0; i < inventory.length; i++) {
    candyObject = inventory[i];
    if (candyObject.inStock < candyObject.weeklyAverage) {
      value = 2 * candyObject.weeklyAverage;
    } else {
      value = 0;
    }
    orderSet[inventory[i].candy] = value;
  }
  return orderSet;
}

I had originally tried to dynamically create the orderSet object using Object.assign, but it didn't work either. Inventory is an array containing candy objects, which has attributes [candy (string), inStock (int), weeklyAverage (int)]. I'm assuming it's some kind of scope issue, but I can't seem to figure it out. Otherwise, I must be missing something about how JS works. Thank you in advance for your help.

Best,

Brian

about 4 years ago · Juan Pablo Isaza
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