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

140
Visualizações
nodejs - array search and append

I need a help from node experts... Version I must use is 0.10.x

I have an array like this:

[ 
    [ 'ABC', '5' ] ,
    [ 'BCD', '1' ]
] 

and I have new values to enter [ 'DDD', '3' ] and [ 'ABC', '4' ] and what I would like to achieve is to search if first column exists in array - if yes sum up second column, if not just add values to the array.

In result I would expect to have:

  1. add [ 'DDD', '3' ] - DDD does not exist in array to it will be added

    [ [ 'ABC', '5' ] , [ 'BCD', '1' ] , [ 'DDD', '3' ] ]

  2. add [ 'ABC', '4' ] - ABC exist in array so second column will be summed up for ABC

    [ [ 'ABC', '9' ] , [ 'BCD', '1' ] , [ 'DDD', '3' ] ]

Please help

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your objects initial value:

var myObj = [{'ABC': '5'}, {'BCD': '1'}]

Now if DDD doesn't exists, just add it:

var DDD = "3"
var DDDExists = false;

myObj.forEach(function(){
  if(this.DDD.length > 0){
    // If it exists, break the loop
    DDDExists = true;
    break;
  }
})

// If DDD doesn't exists, add it
if(DDDExists === false){
  // Add DDD object to array
  myObj.push({'DDD': 3});
}

Now if ABC exists, sum ABC to all the available values:

// Check if ABC exists
var ABCExsits = false;

myObj.forEach(function(){
  if(this.ABC.length > 0){
    // If ABC exits, break the loop
    ABCExists = true;
   break;
  }
})

if(ABCExists === true){

  // Sum all the values
  var totalSum = 0;

  myObj.forEach(function(){
    // Since we don't know the name property of the obj, we need to do a for loop
    for(var prop in this){
      totalSum = totalSum + this[prop];
    }    
  })

  // Now add `totalSum` to ABC

  myObj.foreach(function(){
    if(this.ABC.length > 0){
      this.ABC = totalSum;
      break;
    }
  })

}
over 4 years ago · Santiago Trujillo 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