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

198
Visualizações
How to get the key and value not overwritten inside a for loop in an object?

I have this function that takes two lists as arguments. The first letter of each element of the list "L" is the identification of a book category. For example, "BKWR" and "BTSQ" are same category books because they start with the same letter "B". The positive integer separated by space is the number of books in that category. Now what the function does is that it takes the first list and matches from the second list whether the book category starting with the letter is present or not. If it is present then it sums the number. For example in the list "L" two book categories starting with "B" are present so it is supposed to sum them.

However, rather than summing the two, my function is overwriting the value of the previous "B" category. How can I stop it from overwriting the value?

function extract(list,stocklist){
  let newArr = [];
  for (let i = 0; i < stocklist.length; i++){
    for (let j = 0; j < list.length; j++){
      if (stocklist[i] == list[j][0]){
        newArr.push(list[j]);
      }
    }
  }
  let selected = newArr.map((item) => item.split(' '));
  let extracted = {};
  for (let k = 0; k < selected.length; k++){
    for (let l = 0; l < selected[k].length-1; l++){
        let key = selected[k][l][0];
        let value = selected[k][l+1];
        extracted[key] =  value;
    }
  }
  
  return extracted;
}

let L = ["ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"];
let M = ["A", "B", "W"];

console.log(extract(L,M));

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

0

If there's already a value for the key, add to it instead of overwriting it. So change

extracted[key] =  value;

to

if (key in extracted) {
    extracted[key] += parseInt(value);
} else {
    extracted[key] = parseInt(value);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You actually need to add the "value" to your extracted object:

function extract(list,stocklist){
  let newArr = [];
  for (let i = 0; i < stocklist.length; i++){
    for (let j = 0; j < list.length; j++){
      if (stocklist[i] == list[j][0]){
        newArr.push(list[j]);
      }
    }
  }
  let selected = newArr.map((item) => item.split(' '));
  let extracted = {};
  for (let k = 0; k < selected.length; k++){
    for (let l = 0; l < selected[k].length-1; l++){
        let key = selected[k][l][0];
        let value = selected[k][l+1];
        if(value) {
         extracted[key] = (+extracted[key] || 0) + +value;
       }
    }
  }
  
  return extracted;
}

let L = ["ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"];
let M = ["A", "B", "W"];

console.log(extract(L,M));

about 4 years ago · Juan Pablo Isaza Relatório

0

Here's the minor part you are missing. Check the key and sum up, or simply assign the first value like:

extracted[key] = extracted[key] ? extracted[key] + Number(value) : Number(value);
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