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

202
Visualizações
How to get these 2D array elements summed if there are duplicates?

I have seen a couple of examples, but handling arrays with 2 elements in it and I was wondering what changes would have to be made so that this one gets summed by comparing the first element and calculating the 4th elements

array = 
[
   [2, 'name1','something',15],
   [3, 'name10','something',5],
   [5, 'name20','something',20],
   [2, 'name15','something',3]
]

Expected Result

array = 
[
   [2, 'name1','something',18],
   [3, 'name10','something',5],
   [5, 'name20','something',20]
]

Appreciate your help!

Thanks!

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

0

Just update the array indices of the required elements

In my test case, I changed the indices used in the script. The script used would be as follows:

function myFunction() {
  var array = [
    [2, 'name1', 'something', 15],
    [3, 'name10', 'something', 5],
    [5, 'name20', 'something', 20],
    [2, 'name15', 'something', 3]
  ]
  var result = Object.values(array.reduce((c, v) => {
    if (c[v[0]]) c[v[0]][3] += v[3]; // Updated the indices
    else c[v[0]] = v; // Updated the indices
    return c;
  }, {}));

  console.log(result);
}

From here, index [0] represents the elements in the first column (2,3,5,2) while index [3] represents the elements in the last column (15,5,20,3). So basically, the script only processed the first and last columns to achieve your desired output.

Output

Output

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