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

108
Visualizações
Reduce an array to an 2D array with matching properties

If I have one array of objects with inner properties like so:

var array = [
    {
        "Structure_SortID": "001.001.003",
    },
    {
        "Structure_SortID": "001.001.003",
    },
    {
        "Structure_SortID": "001.001.003",
    },
    {
        "Structure_SortID": "001.001.003",
    },
    {
        "Structure_SortID": "001.004.002",
    },
    {
        "Structure_SortID": "001.004.002",
    }
];

How can I reduce this one array into a single 2D array that contains 2 arrays of matching "Structure_SortID" properties? Output should be:

var array = [
    // Filtered so only 001.004.002
    [
        {
            "Structure_SortID": "001.001.003",
        },
        {
            "Structure_SortID": "001.001.003",
        },
        {
            "Structure_SortID": "001.001.003",
        },
        {
            "Structure_SortID": "001.001.003",
        }
    ],
    // Filtered so only 001.004.002
    [
        {
            "Structure_SortID": "001.004.002",
        },
        {
            "Structure_SortID": "001.004.002",
        }
    ]
];

The solution needs to allow for an infinite number of lists with matching "Structre_SortID" properties. And needs to support situations where there is only 1 array of matching ID's inside the 2D array. And needs to support empty arrays or single item arrays alongside matching lists inside the 2D array.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

function getArrayOfObjectByKey(data, key) {
    return Object.values(
        data.reduce((acc, e) => {
            if (key in e) {
                let value = e[key];
                if (value in acc) {
                    acc[value].push(e);
                } else {
                    acc[value] = [e];
                }
            }
            return acc;
        }, {})
    );
}
getArrayOfObjectByKey(array, 'Structure_SortID');
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