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

158
Vistas
How to group two-dimensional array by value at zero index

Let's say I have the following two-dimensional array:

const array = [[1, 1], [1, 2], [2, 1], [2, 2]];

What I want to do is to find all the values under first index which have common zero index value. So the result should be the following:

[[1, [1, 2]], [2, [1, 2]]]

Or maybe Map would look better:

[Map(1 => [1, 2]), Map(2 => [1, 2])]

How can I do that? With or without lodash. My solution looks a bit bloated and messy:

const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouppedCartItemsMap = new Map();

array.forEach((item) => {
  const [locationId, contractId] = item;

  if (!grouppedCartItemsMap.has(locationId)) {
    grouppedCartItemsMap.set(locationId, [contractId]);
  } else {
    const existingItem = grouppedCartItemsMap.get(locationId);

    if (!existingItem.includes(contractId)) {
      grouppedCartItemsMap.set(locationId, [...existingItem, contractId]);
    }
  }
});
console.log(grouppedCartItemsMap);

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

0

If an object would work:

const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouped = {};
for (const [first, last] of array) {
  grouped[first] ??= [];
  grouped[first].push(last);
}
console.log(grouped);

about 4 years ago · Juan Pablo Isaza Denunciar

0

This looks like a use case for reduce:

const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouppedCartItemsMap = array.reduce((acc, [locationId, contractId]) => {
  if (!acc.has(locationId)) acc.set(locationId, [contractId]);
  else acc.get(locationId).push(contractId);
  return acc;
}, new Map());
console.log([...grouppedCartItemsMap.entries()]);

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