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

184
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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