Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda