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

182
Vistas
Merge arrays based on first value within each array

I have an array that looks like this:

var arr = [
[
    "2021-07-31T00:00:00Z",
    "648429a0-00e5-4752-9d84-2857a0ea0787"
],
[
    "2021-08-31T00:00:00Z",
    "648429a0-00e5-4752-9d84-2857a0ea0787"
],
[
    "2021-07-31T00:00:00Z",
    "AAAA"
],
[
    "2021-08-31T00:00:00Z",
    "BBBB"
]

]

I'd like to transform this based on the first value (the date) of each array. So if the dates match they will merge into one. So the output I'm trying to get is

[
[
    "2021-07-31T00:00:00Z",
    "648429a0-00e5-4752-9d84-2857a0ea0787",
    "AAAA"
],
[
    "2021-08-31T00:00:00Z",
    "648429a0-00e5-4752-9d84-2857a0ea0787",
     "BBBB"
]

]

Would be grateful to know what would be the best approach in this instance.

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

0

Use a map to overwrite the values as they are found in the array. Then use Object.entries() to create the final array:


var original = [ [1,2], [1,3], [2,3]]
var final = []
var map = {}

original.forEach(a => {
    if (!map[a[0]]) { map[a[0]] = [] }
    map[a[0]].push(a[1]);
});
Object.entries(map).forEach(e => final.push([e[0], ...e[1]]))

Edit: Changed the answer to get all the values

about 4 years ago · Juan Pablo Isaza Denunciar

0

The OP's task can be achieved without nested iterations within a single reduce cycle.

The underlying approach is to use a tailored object as accumulator/collector. Such a collector features 2 properties ... index which serves as Object based map/lookup for grouped arrays where the group key is always the 1st item of each (to be) processed array ... and ... result which is going to hold references of the above mentioned (yet to be created) grouped arrays where one does always push the 2nd item of the currently processed array into.

var arr = [[
  "2021-07-31T00:00:00Z",
  "648429a0-00e5-4752-9d84-2857a0ea0787",
], [
  "2021-08-31T00:00:00Z",
  "648429a0-00e5-4752-9d84-2857a0ea0787",
], [
  "2021-07-31T00:00:00Z",
  "AAAA",
], [
  "2021-08-31T00:00:00Z",
  "BBBB",
]];

function collectAndAggregateGroupedArrays(collector, item) {
  const { index, result } = collector;

  let groupKey = item[0];
  let groupedList = index[groupKey];

  if (!groupedList) {
    groupedList = index[groupKey] = [groupKey];

    result.push(groupedList);
  }
  groupedList.push(item[1]);

  return collector;
}
console.log(
  arr.reduce(collectAndAggregateGroupedArrays, {

    index: {},
    result: [],

  }).result
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try this reduce approach

    var arr = [
    [
        "2021-07-31T00:00:00Z",
        "648429a0-00e5-4752-9d84-2857a0ea0787"
    ],
    [
        "2021-08-31T00:00:00Z",
        "648429a0-00e5-4752-9d84-2857a0ea0787"
    ],
    [
        "2021-07-31T00:00:00Z",
        "AAAA"
    ],
    [
        "2021-08-31T00:00:00Z",
        "BBBB"
    ]
];

arr = arr.reduce((a, i) => {
    if (!a) a = [];
    var found = false;
    a.forEach(ai => {
        if (ai[0] == i[0]) {
            found = true;
            for (var k = 0; k < i.length; k++) {
                if (k > 0)
                    ai.push(i[k]);
            }
        }
    });
    if (!found)
        a.push(i);
    return a;
}, []);
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