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

211
Vistas
How to compare adjacent elements in 2D array if duplicate?

I have a 2D array:

var arr1 = [["Egypt","Grid",50],["Egypt","Grid",10],["Nigeria","Grid",20],["Ghana","Grid",60],["Egypt","Grid",30]]

I want to check the first element of each array, e.g. Egypt, Nigeria and Ghana to see if they are duplicates. But I only want it to check against the next element not against all elements in the array. If one or more elements are duplicated next to each other, I want to return one array summing the elements at position 2 (50,10,20,60,30)

This should result in :

var arr2 = [["Egypt","Grid",60],["Nigeria","Grid",20],["Ghana","Grid",60]],["Egypt","Grid",30]]

Note how even though there are 3 arrays with "Egypt", it only combines where they are next to each other.

I have tried both map and for loop but don't have anything that is close to working. This is what I've started with:

arr1.map(function (unit, index, array) {
var length = array.length
if (index < length - 2) {
  var next = array[index + 1][0]
  if (unit[0] === next) {
    }
  }
})

This works to check if elements are duplicates. I think I need to next put the duplicates into a separate array which I can then reduce but am not sure how to do that. Any help in pointing me in the right direction would be great. Thanks!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use a simple for loop iterating over each array except the last and checking if the first element of the current iterated element matches the first element of current+1.

If they match, sum the third elements of each and assign to the current iterated array, delete current+1 (here using splice()) and decrement i to recheck the same index again.

var arr1 = [
  ['Egypt', 'Grid', 50],
  ['Egypt', 'Grid', 10],
  ['Nigeria', 'Grid', 20],
  ['Ghana', 'Grid', 60],
  ['Egypt', 'Grid', 30],
];

for (let i = 0; i < arr1.length - 1; i++) {
  if (arr1[i][0] === arr1[i + 1][0]) {
    arr1[i][2] = arr1[i][2] + arr1[i + 1][2];
    arr1.splice(i + 1, 1);
    i--;
  }
}

console.log(arr1);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can create a grouping array and in which you only push the element if an only if the last elments country and category doesn't match with the last element in the grouping array or if there is no element in the grouping

You can use for..of loop

var arr1 = [
  ["Egypt", "Grid", 50],
  ["Egypt", "Grid", 10],
  ["Nigeria", "Grid", 20],
  ["Ghana", "Grid", 60],
  ["Egypt", "Grid", 30],
];

const grouping = [];

for (let [country, category, num] of arr1) {
  const last = grouping[grouping.length - 1];
  const [lastCountry, lastCategory, lastNum] = last ?? [];

  lastCountry && lastCountry === country && lastCategory === category
    ? (last[2] += num)
    : grouping.push([country, category, num]);
}

console.log(grouping);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here is a solution with reduce. For easing the destructuring I have chosen to first prepend results to the accumulator to then finally reverse that result with reverse:

let arr = [["Egypt","Grid",60],["Nigeria","Grid",20],["Ghana","Grid",60],["Egypt","Grid",30]];

let result = arr.slice(1).reduce(([[x, y, z], ...acc], [a, b, c]) =>
    a === x && b == y ? [[a, b, z + c], ...acc]
                      : [[a, b, c], [x, y, z], ...acc]
, [arr[0]]).reverse();

console.log(result);

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